diff --git a/backend/app/clip_cascade.py b/backend/app/clip_cascade.py index e98d477..43b3de2 100644 --- a/backend/app/clip_cascade.py +++ b/backend/app/clip_cascade.py @@ -297,7 +297,7 @@ async def cascade_from_yt_long(job: dict[str, Any], cfg: dict[str, Any] | None = # ── Shorts (15–20s) ──────────────────────────────────────────────── if bool(settings_map.get("shorts_enabled", False)): try: - if room_id and settings_map.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(room_id, day): + if room_id and settings_map.get("shorts_dedupe_room_day", False) and db.has_shorts_job_for_room_day(room_id, day): out["shorts"] = "dedupe" else: ch = db.pick_shorts_channel(day, settings_map, require_upload_quota=True) @@ -305,43 +305,52 @@ async def cascade_from_yt_long(job: dict[str, Any], cfg: dict[str, Any] | None = out["shorts"] = "no_quota" else: sec = shorts_cut_sec(settings_map) - start = _pick_start(master_sec, sec, (0.45, 0.70)) - jtmp = db.create_shorts_job( - session_id="", - room_pk=room_pk, - room_id=room_id, - source_url=source_url, - anchor_name=anchor, - stream_url=stream_url, - channel_pk=str(ch.get("id") or ""), - push_date=day, - ) - if not jtmp: - out["shorts"] = "create_failed" + ch_id = str(ch.get("id") or "") + if room_id and ch_id and db.has_shorts_job_for_room_day(room_id, day, ch_id): + out["shorts"] = "channel_room_dedupe" else: - jid = str(jtmp["id"]) - dst = str(clips_root / f"{jid}.mp4") - cut = await asyncio.to_thread( - cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec + offset = db.next_shorts_room_clip_offset(room_id, day, clip_sec=sec) if room_id else 0 + # From master file: pick a non-overlapping window near mid, shifted by offset. + start = _pick_start(master_sec, sec, (0.45, 0.70)) + start = min(max(0.0, start + float(offset)), max(0.0, master_sec - sec)) + jtmp = db.create_shorts_job( + session_id="", + room_pk=room_pk, + room_id=room_id, + source_url=source_url, + anchor_name=anchor, + stream_url=stream_url, + channel_pk=ch_id, + push_date=day, + clip_offset_sec=offset, + dedupe_room_global=bool(settings_map.get("shorts_dedupe_room_day", False)), ) - if not cut.get("ok"): - db.update_shorts_job( - jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time() - ) - out["shorts"] = f"cut_fail:{cut.get('error')}" + if not jtmp: + out["shorts"] = "create_failed" else: - from .shorts_schedule import pick_upload_at - - upload_at = pick_upload_at(channel_pk=str(ch.get("id") or ""), cfg=settings_map) - db.update_shorts_job( - jid, - status="scheduled", - clip_path=str(cut["path"]), - clip_seconds=float(cut.get("seconds") or sec), - upload_at=upload_at, - error="cascade_from_yt_long", + jid = str(jtmp["id"]) + dst = str(clips_root / f"{jid}.mp4") + cut = await asyncio.to_thread( + cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec ) - out["shorts"] = jid + if not cut.get("ok"): + db.update_shorts_job( + jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time() + ) + out["shorts"] = f"cut_fail:{cut.get('error')}" + else: + from .shorts_schedule import pick_upload_at + + upload_at = pick_upload_at(channel_pk=str(ch.get("id") or ""), cfg=settings_map) + db.update_shorts_job( + jid, + status="scheduled", + clip_path=str(cut["path"]), + clip_seconds=float(cut.get("seconds") or sec), + upload_at=upload_at, + error="cascade_from_yt_long", + ) + out["shorts"] = jid except Exception as exc: out["shorts"] = f"err:{exc}"[:120] diff --git a/backend/app/clip_retention.py b/backend/app/clip_retention.py index 754c892..476d013 100644 --- a/backend/app/clip_retention.py +++ b/backend/app/clip_retention.py @@ -116,7 +116,28 @@ def _clear_path_refs(path: str, now: float) -> None: with db._lock: conn = db._connect() try: - for table in ("shorts_jobs", "tiktok_jobs", "x_clip_jobs", "yt_long_jobs"): + # Shorts: clearing the file must also unstick scheduled/recorded jobs + # so they re-enter pending (otherwise quota is consumed forever). + try: + conn.execute( + """ + UPDATE shorts_jobs + SET clip_path = '', status = 'pending', upload_at = 0, + clip_seconds = 0, error = '成片被清理,已重新排队录制', + updated_at = ? + WHERE clip_path = ? + AND status IN ('recorded', 'scheduled') + AND IFNULL(youtube_video_id, '') = '' + """, + (now, path), + ) + conn.execute( + "UPDATE shorts_jobs SET clip_path = '', updated_at = ? WHERE clip_path = ?", + (now, path), + ) + except Exception: + pass + for table in ("tiktok_jobs", "x_clip_jobs", "yt_long_jobs"): try: conn.execute( f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?", @@ -250,6 +271,18 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]: if under_pressure and disk_free_gb() >= min_free: break + covers_purge: dict[str, Any] = {} + try: + from . import s3_storage + + try: + keep_days = float(settings_map.get("covers_s3_keep_days") or 2) + except Exception: + keep_days = 2.0 + covers_purge = s3_storage.purge_covers_older_than(keep_days=keep_days) + except Exception as exc: + covers_purge = {"ok": False, "error": str(exc)[:160]} + return { "ok": True, "examined": examined, @@ -260,4 +293,5 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]: "free_gb_before": round(free_before, 2), "free_gb_after": round(disk_free_gb(), 2), "min_free_gb": min_free, + "covers_s3": covers_purge, } diff --git a/backend/app/config.py b/backend/app/config.py index e077aea..ad0f9c7 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -81,6 +81,9 @@ class Settings(BaseSettings): neko_nat1to1: str = "" # empty → auto-detect public IP neko_webrtc_icelite: str = "0" # sh2: OFF for remote ICE stability neko_shm_size: str = "512mb" + # Hard cap per Neko container (Docker). Empty/0 = unlimited. + # VPS ~4Gi: keep one Live Studio under ~1.5Gi so host+API+FFmpeg survive. + neko_mem_limit: str = "1536m" neko_desktop_screen: str = "1024x576@10" neko_max_fps: str = "10" neko_video_bitrate: str = "700" diff --git a/backend/app/db.py b/backend/app/db.py index 3aa483f..b7e09fc 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -237,12 +237,20 @@ def init_db() -> None: sj_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()} if "upload_at" not in sj_cols: conn.execute("ALTER TABLE shorts_jobs ADD COLUMN upload_at REAL NOT NULL DEFAULT 0") + if "clip_offset_sec" not in sj_cols: + conn.execute( + "ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0" + ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_upload ON shorts_jobs(status, upload_at)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_day ON shorts_jobs(room_id, push_date, status)" ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_ch_day " + "ON shorts_jobs(room_id, channel_pk, push_date, status)" + ) conn.executescript( """ CREATE TABLE IF NOT EXISTS tiktok_channels ( @@ -582,12 +590,15 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "youtube_relay_exclusive_live": True, # Time-slot mode: N=keyed channels → each gets 24/N Beijing hours; source=live Douyin rooms. "youtube_relay_time_slot_mode": False, + # Manual rotate for quick time_slot testing (ignores real 24/N clock). + "youtube_relay_timeslot_test": False, + "youtube_relay_timeslot_test_group_id": "", # Shorts pipeline "shorts_enabled": False, "shorts_clip_sec": 15, "shorts_trigger": "tagged", "shorts_tag": "shorts", - "shorts_dedupe_room_day": True, + "shorts_dedupe_room_day": False, "shorts_max_concurrent": 1, "shorts_auto_upload": True, "shorts_live_sample": True, @@ -595,8 +606,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "shorts_live_sample_batch": 1, "shorts_sample_any_live": True, "shorts_upload_spread": True, - "shorts_upload_min_gap_sec": 720, - "shorts_channel_min_gap_sec": 2400, + "shorts_upload_min_gap_sec": 600, + "shorts_channel_min_gap_sec": 600, "shorts_delete_clip_after_upload": True, "shorts_auto_retry_failed": True, "shorts_auto_retry_max_attempts": 3, @@ -620,6 +631,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "yt_studio_cookies_by_profile": {}, "shorts_gcp_project_id": "live-473104", "shorts_yt_daily_upload_limit": 90, + # After real YouTube 429, auto-upload cool-down per Client (sec); manual never gated + "shorts_yt_quota_cooldown_sec": 3600, "shorts_yt_upload_blocked_until": 0, "shorts_yt_uploads_pt_date": "", "shorts_yt_uploads_pt_count": 0, @@ -710,6 +723,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "clip_cascade_enabled": True, "clips_max_age_hours": 24, "clips_min_free_gb": 12, + # Seaweed/S3 session covers (covers/*.jpg); avatars kept. Default 2 days. + "covers_s3_keep_days": 2, "yt_long_monetize_when_ypp": True, "tiktok_auto_retry_failed": False, "tiktok_auto_retry_max_attempts": 3, @@ -3783,7 +3798,7 @@ def shorts_live_channel_stats(*, date_from: str = "", date_to: str = "") -> list conn.close() -# Jobs that consume a channel's Beijing-day quota (aligned with schedule_board.used). +# Jobs that occupy a Beijing-day pipeline slot (pending→done). Cap enqueue with this. _SHORTS_QUOTA_STATUSES = ( "pending", "recording", @@ -3793,9 +3808,45 @@ _SHORTS_QUOTA_STATUSES = ( "uploaded", "done", ) +# Progress / 已满 / daily_min: only successful uploads count. +_SHORTS_UPLOADED_STATUSES = ("uploaded", "done") + + +def shorts_channel_last_slot_ts(channel_pk: str, push_date: str) -> float: + """Latest upload slot time for channel today (scheduled/uploading/finished).""" + cid = str(channel_pk or "").strip() + day = str(push_date or "").strip() + if not cid or not day: + return 0.0 + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT status, upload_at, finished_at, updated_at FROM shorts_jobs + WHERE channel_pk = ? AND push_date = ? + AND status IN ('scheduled', 'recorded', 'uploading', 'uploaded', 'done') + """, + (cid, day), + ).fetchall() + best = 0.0 + for r in rows: + st = str(r["status"] or "") + if st in {"uploaded", "done"}: + ts = float(r["finished_at"] or r["updated_at"] or 0) + elif st == "uploading": + ts = float(r["updated_at"] or r["upload_at"] or 0) + else: + ts = float(r["upload_at"] or r["updated_at"] or 0) + if ts > best: + best = ts + return best + finally: + conn.close() def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int: + """Pipeline occupancy (pending…done). Used to cap new enqueues.""" placeholders = ",".join("?" for _ in _SHORTS_QUOTA_STATUSES) with _lock: conn = _connect() @@ -3813,8 +3864,27 @@ def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int: conn.close() +def shorts_channel_uploaded_count(channel_pk: str, push_date: str) -> int: + """Successful uploads only (uploaded/done). Progress bar / 已满 / daily_min.""" + placeholders = ",".join("?" for _ in _SHORTS_UPLOADED_STATUSES) + with _lock: + conn = _connect() + try: + row = conn.execute( + f""" + SELECT COUNT(*) AS c FROM shorts_jobs + WHERE channel_pk = ? AND push_date = ? + AND status IN ({placeholders}) + """, + (channel_pk, push_date, *_SHORTS_UPLOADED_STATUSES), + ).fetchone() + return int(row["c"] if row else 0) + finally: + conn.close() + + def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]: - """Per enabled channel: used/gap toward daily_max for the Beijing day.""" + """Per enabled channel: progress = uploaded; pipeline caps enqueue.""" day = push_date or push_date_from_ts(time.time()) rows: list[dict[str, Any]] = [] for ch in list_shorts_channels(enabled=True): @@ -3823,17 +3893,21 @@ def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]: daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) if daily_max < daily_min: daily_max = daily_min - used = shorts_channel_upload_count(cid, day) + pipeline = shorts_channel_upload_count(cid, day) + uploaded = shorts_channel_uploaded_count(cid, day) rows.append( { "id": cid, "name": ch.get("name"), "daily_min": daily_min, "daily_max": daily_max, - "used": used, - "gap": max(0, daily_max - used), - "min_met": used >= daily_min, - "max_met": used >= daily_max, + "used": uploaded, + "uploaded": uploaded, + "pipeline": pipeline, + "gap": max(0, daily_max - uploaded), + "min_met": uploaded >= daily_min, + "max_met": uploaded >= daily_max, + "pipeline_full": pipeline >= daily_max, } ) rows.sort(key=lambda r: (0 if not r["min_met"] else 1, r["used"], r["id"])) @@ -3998,13 +4072,16 @@ def pick_shorts_channel( pid = profile_id_for_channel(ch) if require_upload_quota and not project_uploads_available(cfg, profile_id=pid): continue - used = shorts_channel_upload_count(str(ch["id"]), push_date) + cid = str(ch["id"]) + pipeline = shorts_channel_upload_count(cid, push_date) + uploaded = shorts_channel_uploaded_count(cid, push_date) daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) - if used >= daily_max: + # Cap new jobs by pipeline; progress target is uploaded. + if pipeline >= daily_max or uploaded >= daily_max: continue daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE) - under = 0 if used < daily_min else 1 - scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch)) + under = 0 if uploaded < daily_min else 1 + scored.append((under, uploaded, float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None scored.sort(key=lambda x: (x[0], x[1], x[2])) @@ -4061,6 +4138,45 @@ def get_shorts_job(job_id: str) -> dict[str, Any] | None: conn.close() +def next_shorts_room_clip_offset( + room_id: str, + push_date: str, + *, + clip_sec: int = 15, +) -> int: + """Next non-overlapping live window for this room today (0, 15, 30, …).""" + rid = str(room_id or "").strip() + day = str(push_date or "").strip() or push_date_from_ts(time.time()) + sec = max(10, min(int(clip_sec or 15), 60)) + if not rid: + return 0 + with _lock: + conn = _connect() + try: + cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()} + if "clip_offset_sec" not in cols: + return 0 + rows = conn.execute( + """ + SELECT clip_offset_sec FROM shorts_jobs + WHERE room_id = ? AND push_date = ? + AND status NOT IN ('failed', 'skipped') + """, + (rid, day), + ).fetchall() + if not rows: + return 0 + best = 0.0 + for r in rows: + try: + best = max(best, float(r["clip_offset_sec"] or 0)) + except (TypeError, ValueError, KeyError): + continue + return int(best) + sec + finally: + conn.close() + + def create_shorts_job( *, session_id: str, @@ -4072,38 +4188,64 @@ def create_shorts_job( channel_pk: str = "", push_date: str = "", force: bool = False, + clip_offset_sec: float | int = 0, + dedupe_room_global: bool = False, ) -> dict[str, Any] | None: - """Create a Shorts job. Same room_id + Beijing day is unique unless force=True. + """Create a Shorts job. - Returns None when a non-failed/skipped job already exists for that room/day. + Default: unique per (room_id, channel_pk, Beijing day) — different channels may + share one Douyin room if each gets a distinct clip_offset_sec (sequential live + windows: 0–15s, 15–30s, …). + + dedupe_room_global=True restores legacy one-job-per-room-per-day. """ now = time.time() jid = str(uuid.uuid4()) day = push_date or push_date_from_ts(now) rid = str(room_id or "").strip() + ch = str(channel_pk or "").strip() + offset = max(0, int(float(clip_offset_sec or 0))) with _lock: conn = _connect() try: + cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()} + if "clip_offset_sec" not in cols: + conn.execute( + "ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0" + ) if rid and not force: - existing = conn.execute( - """ - SELECT * FROM shorts_jobs - WHERE room_id = ? AND push_date = ? - AND status NOT IN ('failed', 'skipped') - ORDER BY created_at ASC - LIMIT 1 - """, - (rid, day), - ).fetchone() - if existing: - return None + if dedupe_room_global: + existing = conn.execute( + """ + SELECT id FROM shorts_jobs + WHERE room_id = ? AND push_date = ? + AND status NOT IN ('failed', 'skipped') + LIMIT 1 + """, + (rid, day), + ).fetchone() + if existing: + return None + elif ch: + existing = conn.execute( + """ + SELECT id FROM shorts_jobs + WHERE room_id = ? AND push_date = ? AND channel_pk = ? + AND status NOT IN ('failed', 'skipped') + LIMIT 1 + """, + (rid, day, ch), + ).fetchone() + if existing: + return None conn.execute( """ INSERT INTO shorts_jobs( id, session_id, room_pk, room_id, source_url, anchor_name, stream_url, channel_pk, status, clip_path, clip_seconds, youtube_video_id, youtube_url, - error, push_date, attempts, created_at, updated_at, started_at, finished_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, ?, ?, 0, 0) + error, push_date, attempts, created_at, updated_at, started_at, finished_at, + clip_offset_sec + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, ?, ?, 0, 0, ?) """, ( jid, @@ -4117,6 +4259,7 @@ def create_shorts_job( day, now, now, + float(offset), ), ) if channel_pk: @@ -4135,11 +4278,17 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None: "status", "clip_path", "clip_seconds", + "clip_offset_sec", "youtube_video_id", "youtube_url", "error", "channel_pk", "stream_url", + "source_url", + "anchor_name", + "room_id", + "room_pk", + "session_id", "attempts", "started_at", "finished_at", @@ -4219,9 +4368,40 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A" if pid in skip: continue + jid = row["id"] + status = row["status"] + ch_pk = str(row["channel_pk"] or "") + day = str(row["push_date"] or "") + # Enforce >10min same-channel spacing at claim time. + if ch_pk and day: + sibs = conn.execute( + """ + SELECT status, upload_at, finished_at, updated_at FROM shorts_jobs + WHERE channel_pk = ? AND push_date = ? AND id != ? + AND status IN ('uploading', 'uploaded', 'done') + """, + (ch_pk, day, jid), + ).fetchall() + last_ts = 0.0 + for r in sibs: + st = str(r["status"] or "") + if st in {"uploaded", "done"}: + ts = float(r["finished_at"] or r["updated_at"] or 0) + else: + ts = float(r["updated_at"] or r["upload_at"] or 0) + if ts > last_ts: + last_ts = ts + if last_ts > 0 and (now - last_ts) < 600.0: + defer_to = last_ts + 600.0 + 15.0 + conn.execute( + "UPDATE shorts_jobs SET upload_at = ?, updated_at = ? WHERE id = ? AND status = ?", + (defer_to, now, jid, status), + ) + continue picked = row break if not picked: + conn.commit() return None jid = picked["id"] status = picked["status"] @@ -4243,7 +4423,6 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict finally: conn.close() - def claim_pending_shorts_record() -> dict[str, Any] | None: """Claim one pending job for recording.""" now = time.time() @@ -4384,37 +4563,45 @@ def reconcile_false_failed_shorts(*, limit: int = 200) -> int: def reconcile_missing_shorts_clips(*, limit: int = 200) -> int: - """Reset jobs whose clip_path points to a deleted file → pending re-record.""" + """Reset jobs whose clip is missing or empty → pending re-record. + + Retention may clear clip_path while leaving status=scheduled; those jobs + consume daily quota but can never upload — reclaim them. + """ from pathlib import Path with _lock: conn = _connect() try: + lim = max(1, min(int(limit), 500)) rows = conn.execute( """ - SELECT id, clip_path FROM shorts_jobs - WHERE clip_path != '' - AND status IN ('recorded', 'scheduled', 'uploading') + SELECT id, clip_path, status FROM shorts_jobs + WHERE status IN ('recorded', 'scheduled', 'uploading') + AND IFNULL(youtube_video_id, '') = '' ORDER BY updated_at DESC LIMIT ? """, - (max(1, min(int(limit), 500)),), + (lim,), ).fetchall() fixed = 0 now = time.time() for row in rows: path = str(row["clip_path"] or "").strip() - if not path or Path(path).is_file(): + missing = (not path) or (not Path(path).is_file()) + if not missing: continue + reason = "成片路径为空,已重新排队录制" if not path else "成片已丢失,已重新排队录制" conn.execute( """ UPDATE shorts_jobs SET status = 'pending', clip_path = '', clip_seconds = 0, - upload_at = 0, error = '成片已丢失,已重新排队录制', + upload_at = 0, error = ?, finished_at = 0, updated_at = ? WHERE id = ? AND status IN ('recorded', 'scheduled', 'uploading') + AND IFNULL(youtube_video_id, '') = '' """, - (now, row["id"]), + (reason, now, row["id"]), ) if conn.total_changes: fixed += 1 @@ -4828,6 +5015,13 @@ def list_auto_retry_failed_jobs(*, max_attempts: int = 3, limit: int = 8) -> lis continue if _classify_shorts_error(err) == "quota": continue + # Offline / dead stream — do not burn record slots retrying. + if "无法获取直播流" in err or "已停播" in err or "已释放名额" in err: + continue + if "probe 404" in low or "server returned 404" in low: + continue + if "connection timed out" in low and ("stream" in low or "http" in low or "opening input" in low): + continue out.append(job) return out finally: diff --git a/backend/app/douyin.py b/backend/app/douyin.py index 44e1bba..0bab435 100644 --- a/backend/app/douyin.py +++ b/backend/app/douyin.py @@ -61,11 +61,38 @@ def _pick_stream_url(room: dict[str, Any]) -> str: return cands[0] if cands else "" +def _is_uhd_stream_url(url: str) -> bool: + """True when CDN path/query looks like origin/UHD (expensive to software-decode).""" + u = str(url or "").lower() + if not u: + return False + return ( + "_uhd" in u + or "/uhd" in u + or "uhd." in u + or "_flv_uhd" in u + or "unique_id=" in u and "_uhd" in u + ) + + +def _demote_uhd_urls(urls: list[str]) -> list[str]: + """Stable partition: non-UHD first, UHD/ORIGIN last (fallback only).""" + good: list[str] = [] + uhd: list[str] = [] + for u in urls: + (uhd if _is_uhd_stream_url(u) else good).append(u) + return good + uhd + + def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list[str]: """Build ordered playable URLs — aligned with DouyinLiveRecorder stream.get_douyin_stream_url. Prefer FLV for Douyin (DLR select_source_url), but keep HLS fallbacks because CDN FLV - lines often 404; quality ladder ORIGIN → FULL_HD1 → HD1 → SD1 → SD2. + lines often 404. + + Quality ladder prefers **non-UHD** to keep FFmpeg CPU sane on VPS: + HD1 → FULL_HD1 → SD1 → SD2 → ORIGIN (last). Any URL whose path looks like `_uhd` + is demoted to the end even if Douyin labeled it otherwise. """ stream = room.get("stream_url") or {} if not isinstance(stream, dict): @@ -76,7 +103,8 @@ def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list flv_map = {} if not isinstance(hls_map, dict): hls_map = {} - order = ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2") + # ORIGIN last — often maps to UHD and burns a full core on soft decode. + order = ("HD1", "FULL_HD1", "SD1", "SD2", "ORIGIN") flv_list: list[str] = [] hls_list: list[str] = [] for key in order: @@ -101,6 +129,8 @@ def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list single_hls = str(stream.get("hls_pull_url") or "").strip() if single_hls.startswith("http") and single_hls not in hls_list: hls_list.append(single_hls) + flv_list = _demote_uhd_urls(flv_list) + hls_list = _demote_uhd_urls(hls_list) if prefer == "hls": return hls_list + flv_list return flv_list + hls_list diff --git a/backend/app/main.py b/backend/app/main.py index d02060a..e1d7953 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -27,6 +27,7 @@ import httpx from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage from . import yt_assign_db +from . import yt_stream_key_db from .config import settings from .cover import cover_path_for, ensure_session_cover from .douyin import check_room @@ -65,6 +66,9 @@ from .models import ( YtAssignGroupUpdate, YtAssignPoolAdd, YtAssignPoolUpdate, + YtStreamKeyEntryUpsert, + YtStreamKeyImportAssignBody, + YtStreamKeyImportBody, ) from .monitor import monitor from .stats import summarize_anchor_schedule, summarize_sessions @@ -131,13 +135,19 @@ async def lifespan(_: FastAPI): raise while True: try: - await asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30) + # Skip pile-up when a rebuild is already running (force waits on same lock). + task = getattr(youtube_live, "_REFRESH_TASK", None) + lock = youtube_live._refresh_lock() # noqa: SLF001 + if (task is not None and not task.done()) or lock.locked(): + pass + else: + await asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30) except asyncio.CancelledError: raise except Exception: pass try: - await asyncio.sleep(30) + await asyncio.sleep(45) except asyncio.CancelledError: raise @@ -174,6 +184,12 @@ async def lifespan(_: FastAPI): asyncio.create_task(_ops_background_loops()) async def _start_workers() -> None: + # Let uvicorn bind + serve /api/health before heavy sync boots (docker/neko/SQLite). + # Otherwise Recv-Q climbs for minutes while the event loop is wedged in worker start. + try: + await asyncio.sleep(3) + except asyncio.CancelledError: + raise if _desktop_light: return @@ -303,9 +319,13 @@ async def ping() -> dict[str, Any]: return {"ok": True, "t": time.time(), "desktop_light": _DESKTOP_LIGHT} +_HEALTH_DEPS_CACHE: dict[str, Any] = {"at": 0.0, "payload": None} +_HEALTH_DEPS_TTL = float(os.environ.get("DY_HEALTH_DEPS_TTL", "5") or "5") + + @app.get("/api/health") async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]: - """Fast health — no full pipeline builders unless ?detail=1.""" + """Fast health — default path must not touch thread pools or SQLite.""" if _DESKTOP_LIGHT: return {"ok": True, "time": time.time(), "desktop_light": True} out: dict[str, Any] = { @@ -348,20 +368,95 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]: }, } + # Default liveness stays cheap, but still expose the fields the ops panel reads + # so a missing youtube/pb/s3 key is not shown as "异常/已停". + if not detail: + try: + out["monitor"] = { + "running": bool( + getattr(monitor, "_task", None) and not monitor._task.done() # noqa: SLF001 + ), + } + out["youtube_monitor"] = { + "running": bool( + getattr(yt_monitor, "_task", None) and not yt_monitor._task.done() # noqa: SLF001 + ), + } + out["shorts"] = { + "running": bool( + getattr(shorts_pipeline, "_task", None) and not shorts_pipeline._task.done() # noqa: SLF001 + ), + } + out["youtube_relay"] = { + "running": bool( + getattr(youtube_relay_pipeline, "_task", None) + and not youtube_relay_pipeline._task.done() # noqa: SLF001 + ), + } + except Exception: + pass + # Cache youtube/pb/s3 pulses — ops/UI poll health often; identical shape, ≤TTL lag. + now_deps = time.time() + cached_deps = _HEALTH_DEPS_CACHE.get("payload") + if ( + isinstance(cached_deps, dict) + and now_deps - float(_HEALTH_DEPS_CACHE.get("at") or 0) < _HEALTH_DEPS_TTL + ): + out.update(cached_deps) + out["deps_cached"] = True + return out + deps: dict[str, Any] = {} + try: + deps["youtube"] = await asyncio.wait_for(youtube_client.health(), timeout=0.6) + except Exception as exc: + deps["youtube"] = {"ok": False, "error": str(exc)[:120], "service": "youtube-svc"} + try: + deps["pocketbase"] = await asyncio.wait_for(pb_sync.health(), timeout=0.5) + except Exception as exc: + deps["pocketbase"] = {"ok": False, "error": str(exc)[:120]} + try: + from . import s3_storage + + enabled = bool(s3_storage.s3_enabled()) + s3_info: dict[str, Any] = { + "enabled": enabled, + "ok": False, + "endpoint": settings.s3_endpoint, + "bucket": settings.s3_bucket, + "public_base": settings.s3_public_base, + } + if enabled: + try: + await asyncio.wait_for( + asyncio.to_thread( + lambda: s3_storage._client().head_bucket(Bucket=settings.s3_bucket) # noqa: SLF001 + ), + timeout=0.6, + ) + s3_info["ok"] = True + except Exception as exc: + s3_info["error"] = str(exc)[:80] + deps["s3"] = s3_info + except Exception: + deps["s3"] = {"enabled": False, "ok": False} + _HEALTH_DEPS_CACHE["at"] = now_deps + _HEALTH_DEPS_CACHE["payload"] = deps + out.update(deps) + out["deps_cached"] = False + return out + try: - if detail: - out["monitor"] = await asyncio.to_thread(monitor.status) - out["shorts"] = await asyncio.to_thread(shorts_pipeline.status) - out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status) - out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status) - out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status) - cfg = await _db(db.get_settings_map) - out["tiktok"] = {"enabled": bool(cfg.get("tiktok_enabled"))} - else: - light = await asyncio.to_thread(_light_health) - out.update(light) + out["monitor"] = await asyncio.to_thread(monitor.status) + out["shorts"] = await asyncio.to_thread(shorts_pipeline.status) + out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status) + out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status) + out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status) + cfg = await _db(db.get_settings_map) + out["tiktok"] = {"enabled": bool(cfg.get("tiktok_enabled"))} + out.update({k: v for k, v in _light_health().items() if k not in out}) except Exception as exc: out["status_error"] = str(exc)[:120] + return out async def _pb() -> dict[str, Any]: try: @@ -2503,14 +2598,15 @@ async def patch_settings(body: SettingsUpdate, request: Request) -> dict[str, An @app.post("/api/settings/sync-cookie") async def sync_cookie_from_sh2() -> dict[str, Any]: """Pull 抖音cookie from sh2 d2ypp2/config/config.ini into settings.""" - result = cookie_loader.force_sync_cookie_from_sh2() + result = await _db(cookie_loader.force_sync_cookie_from_sh2) if not result.get("ok"): raise HTTPException(404, "未找到 sh2 config.ini 中的抖音cookie") - cfg = db.get_settings_map() + cfg = await _db(db.get_settings_map) + mon = await asyncio.to_thread(monitor.status) return { **result, "has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()), - "monitor": monitor.status(), + "monitor": mon, } @@ -3015,7 +3111,7 @@ async def yt_assign_list_groups() -> dict[str, Any]: yt_assign_db.ensure_default_assign_data() except Exception: pass - return yt_assign_db.list_groups(include_urls=True) + return yt_assign_db.list_groups(include_urls=True, include_secret=True) return {"groups": await _db(_load)} @@ -3027,11 +3123,99 @@ async def yt_assign_schedule() -> dict[str, Any]: yt_assign_db.ensure_default_assign_data() except Exception: pass - return yt_assign_db.build_rotation_schedule(include_urls=True) + sched = yt_assign_db.build_rotation_schedule(include_urls=True) + try: + cfg = db.get_settings_map() + if bool(cfg.get("youtube_relay_timeslot_test")): + return yt_assign_db.overlay_timeslot_test_schedule( + sched, + test_on=True, + test_group_id=str(cfg.get("youtube_relay_timeslot_test_group_id") or ""), + ) + except Exception: + pass + return yt_assign_db.overlay_timeslot_test_schedule(sched, test_on=False) return await _db(_load) +# ---------- YouTube stream-key registry (archive only; never touches Neko) ---------- + + +@app.get("/api/youtube/stream-keys") +async def yt_stream_keys_list( + include_secret: bool = Query(True), +) -> dict[str, Any]: + return await asyncio.to_thread(yt_stream_key_db.list_entries, include_secret=bool(include_secret)) + + +@app.get("/api/youtube/stream-keys/export") +async def yt_stream_keys_export() -> dict[str, Any]: + return await asyncio.to_thread(yt_stream_key_db.export_all) + + +@app.post("/api/youtube/stream-keys") +async def yt_stream_keys_upsert(body: YtStreamKeyEntryUpsert) -> dict[str, Any]: + try: + row = await asyncio.to_thread( + yt_stream_key_db.upsert_entry, + entry_id=body.id, + name=body.name, + youtube_channel_id=body.youtube_channel_id, + channel_pk=body.channel_pk, + assign_group_id=body.assign_group_id, + stream_key=body.stream_key, + note=body.note, + sort_order=body.sort_order, + ) + return {"ok": True, "item": row} + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + +@app.get("/api/youtube/stream-keys/{entry_id}") +async def yt_stream_keys_get( + entry_id: str, + include_secret: bool = Query(True), +) -> dict[str, Any]: + row = await asyncio.to_thread( + yt_stream_key_db.get_entry, entry_id, include_secret=bool(include_secret) + ) + if not row: + raise HTTPException(404, "not found") + return {"ok": True, "item": row} + + +@app.delete("/api/youtube/stream-keys/{entry_id}") +async def yt_stream_keys_delete(entry_id: str) -> dict[str, Any]: + ok = await asyncio.to_thread(yt_stream_key_db.delete_entry, entry_id) + if not ok: + raise HTTPException(404, "not found") + return {"ok": True} + + +@app.post("/api/youtube/stream-keys/import-assign") +async def yt_stream_keys_import_assign( + body: YtStreamKeyImportAssignBody | None = None, +) -> dict[str, Any]: + raw = body or YtStreamKeyImportAssignBody() + return await asyncio.to_thread( + yt_stream_key_db.import_from_assign_groups, replace=bool(raw.replace) + ) + + +@app.post("/api/youtube/stream-keys/import") +async def yt_stream_keys_import(body: YtStreamKeyImportBody) -> dict[str, Any]: + try: + return await asyncio.to_thread( + yt_stream_key_db.import_payload, + body.items or [], + replace=bool(body.replace), + ) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/youtube/assign/groups") async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]: try: @@ -3068,6 +3252,12 @@ async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> di ) if prev and prev.get("enabled") and not g.get("enabled"): await youtube_relay_pipeline.stop_group(group_id) + # Disarm time-slot ⇒ leave 24/N like missing key — stop auto push if any. + if prev and yt_assign_db.group_is_time_slot(prev): + was_armed = yt_assign_db.group_time_slot_armed(prev) + now_armed = yt_assign_db.group_time_slot_armed(g) + if was_armed and not now_armed: + await youtube_relay_pipeline.stop_group(group_id) return {"ok": True, "group": g} except ValueError as exc: raise HTTPException(400, str(exc)) from exc @@ -3135,7 +3325,7 @@ async def youtube_relay_exclusive_live(body: dict[str, Any]) -> dict[str, Any]: @app.post("/api/youtube/relay/time-slot-mode") async def youtube_relay_time_slot_mode(body: dict[str, Any]) -> dict[str, Any]: - """Toggle 时间段模式: keyed channels share 24h; source = live Douyin rooms; exclusive Neko/FFmpeg.""" + """Toggle 时间段模式: keyed「时间段」频道平分 24h;源=监控在播抖音。不强制独占、不开自动推流。""" enabled = body.get("enabled") if enabled is None: enabled = body.get("on") @@ -3144,6 +3334,29 @@ async def youtube_relay_time_slot_mode(body: dict[str, Any]) -> dict[str, Any]: return await youtube_relay_pipeline.set_time_slot_mode(bool(enabled)) +@app.post("/api/youtube/relay/timeslot-test") +async def youtube_relay_timeslot_test(body: dict[str, Any]) -> dict[str, Any]: + """Toggle time_slot test mode: force one channel as winner (ignore real 24/N clock).""" + enabled = body.get("enabled") + if enabled is None: + enabled = body.get("on") + if enabled is None: + raise HTTPException(400, "缺少 enabled") + try: + return await youtube_relay_pipeline.set_timeslot_test_mode(bool(enabled)) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + +@app.post("/api/youtube/relay/timeslot-test/next") +async def youtube_relay_timeslot_test_next() -> dict[str, Any]: + """Advance test winner to the next time_slot channel (starts auto relay + Neko/FFmpeg rotate).""" + try: + return await youtube_relay_pipeline.timeslot_test_next() + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/youtube/relay/process_monitor") async def youtube_relay_process_monitor() -> dict[str, Any]: """PM2-compatible process monitor snapshot (cloud pipeline).""" @@ -3216,8 +3429,12 @@ async def youtube_neko_status() -> dict[str, Any]: @app.post("/api/youtube/studio/ingest") @app.post("/hub/youtube/live/ingest") async def youtube_studio_ingest(body: dict[str, Any] | None = None) -> dict[str, Any]: - """Ingest from Neko live-ops Chrome extension (sh2-compatible).""" - return await asyncio.to_thread(youtube_neko.ingest_studio_telemetry, body or {}) + """Ingest from Neko live-ops Chrome extension (sh2-compatible). + + Memory path is cheap; avoid default thread-pool saturation under many tabs. + Occasional disk rewrite stays debounced inside ingest_studio_telemetry. + """ + return youtube_neko.ingest_studio_telemetry(body or {}) @app.get("/api/youtube/studio/samples") @@ -3242,6 +3459,25 @@ async def youtube_studio_samples( return {"ok": True, "count": len(rows), "samples": rows} +@app.get("/api/youtube/assign/groups/{group_id}/analytics") +async def youtube_assign_group_analytics(group_id: str, days: int = 30) -> dict[str, Any]: + """Per-channel live analytics: Studio sessions, daily rollup, rooms, relay pushes.""" + from . import yt_studio_db + + data = await asyncio.to_thread(yt_studio_db.build_group_analytics, group_id, days=days) + if not data.get("ok"): + raise HTTPException(404 if data.get("error") == "group_not_found" else 400, data.get("error") or "error") + return data + + +@app.get("/api/youtube/assign/analytics/sources") +async def youtube_assign_fleet_source_analytics(days: int = 30) -> dict[str, Any]: + """Fleet matrix: which Douyin room performs best on which YouTube channel (for scheduling).""" + from . import yt_studio_db + + return await asyncio.to_thread(yt_studio_db.build_fleet_source_matrix, days=days) + + @app.post("/api/youtube/neko/instances/{instance_id}/{action}") async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: try: diff --git a/backend/app/models.py b/backend/app/models.py index 46dc356..141ff77 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -373,6 +373,8 @@ class YtAssignGroupCreate(BaseModel): enabled: bool = True # normal = 手动推流(精选); time_slot = 时间段排班推流 category: str = "normal" + # time_slot cards: participate in 24/N (off ≡ no stream key for schedule) + time_slot_armed: bool = True class YtAssignGroupUpdate(BaseModel): @@ -385,6 +387,7 @@ class YtAssignGroupUpdate(BaseModel): sort_order: Optional[int] = None neko_enabled: Optional[bool] = None category: Optional[str] = None + time_slot_armed: Optional[bool] = None class YtAssignPoolAdd(BaseModel): @@ -428,6 +431,26 @@ class YtAssignAutoFillBody(BaseModel): force: bool = False +class YtStreamKeyEntryUpsert(BaseModel): + id: str = "" + name: str = "" + youtube_channel_id: str = "" + channel_pk: str = "" + assign_group_id: str = "" + stream_key: str = "" + note: str = "" + sort_order: Optional[int] = None + + +class YtStreamKeyImportBody(BaseModel): + items: list[dict[str, Any]] = Field(default_factory=list) + replace: bool = False + + +class YtStreamKeyImportAssignBody(BaseModel): + replace: bool = False + + class YouTubeVideoUpdate(BaseModel): title: Optional[str] = None description: Optional[str] = None diff --git a/backend/app/network_hub.py b/backend/app/network_hub.py index f47b7b0..cfa6006 100644 --- a/backend/app/network_hub.py +++ b/backend/app/network_hub.py @@ -130,7 +130,20 @@ def _wg_handshake_age_sec() -> int | None: return None +_ping_wg_cache: tuple[float, dict[str, Any]] | None = None +_PING_WG_CACHE_TTL_SEC = 15.0 + + def _ping_wg_peer() -> dict[str, Any]: + global _ping_wg_cache + import time as _time + + now = _time.time() + if _ping_wg_cache is not None: + cached_at, cached = _ping_wg_cache + if now - cached_at < _PING_WG_CACHE_TTL_SEC: + return dict(cached) + if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False: peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1" else: @@ -143,7 +156,9 @@ def _ping_wg_peer() -> dict[str, Any]: m = re.search(r"time[=<]([0-9.]+)\s*ms", out) if m: rtt = m.group(1) + "ms" - return {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]} + result = {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]} + _ping_wg_cache = (now, result) + return dict(result) def wireguard_watch_status() -> dict[str, Any]: @@ -175,16 +190,18 @@ def network_overview() -> dict[str, Any]: frp = frp_status() from . import egress_hub + # One ShellCrash status for this request (status() itself is also TTL-cached). + sc = shellcrash_hub.status() return { "ok": True, "path_roles": path_roles(), "wireguard": wg, "frp": frp, - "shellcrash": shellcrash_hub.status(), + "shellcrash": sc, "socks": socks_status(), "egress": egress_hub.status(), "deploy_shape": _deploy_shape_hint(), - "physical_checklist": physical_checklist(wg=wg, frp=frp), + "physical_checklist": physical_checklist(wg=wg, frp=frp, shellcrash=sc), } @@ -192,6 +209,7 @@ def physical_checklist( *, wg: dict[str, Any] | None = None, frp: dict[str, Any] | None = None, + shellcrash: dict[str, Any] | None = None, ) -> dict[str, Any]: """Operator checklist — WireGuard primary, FRP auxiliary.""" checks: list[dict[str, Any]] = [] @@ -247,7 +265,7 @@ def physical_checklist( f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务", ) - sc = shellcrash_hub.status() + sc = shellcrash if isinstance(shellcrash, dict) else shellcrash_hub.status() if shape.startswith("physical"): add( "shellcrash", diff --git a/backend/app/pb_sync.py b/backend/app/pb_sync.py index 1d554d0..bf2244c 100644 --- a/backend/app/pb_sync.py +++ b/backend/app/pb_sync.py @@ -16,6 +16,11 @@ from .config import settings _token: str = "" _token_expire: float = 0 +_pb_fail_count: int = 0 +_pb_circuit_until: float = 0.0 +_PB_TIMEOUT_SEC = 6.0 +_PB_CIRCUIT_FAILS = 3 +_PB_CIRCUIT_COOLDOWN_SEC = 60.0 def _pb_id(sqlite_id: str) -> str: @@ -23,10 +28,28 @@ def _pb_id(sqlite_id: str) -> str: return hashlib.md5(str(sqlite_id).encode("utf-8")).hexdigest()[:15] +def _pb_circuit_open() -> bool: + return time.time() < _pb_circuit_until + + +def _pb_note_success() -> None: + global _pb_fail_count, _pb_circuit_until + _pb_fail_count = 0 + _pb_circuit_until = 0.0 + + +def _pb_note_failure() -> None: + global _pb_fail_count, _pb_circuit_until + _pb_fail_count += 1 + if _pb_fail_count >= _PB_CIRCUIT_FAILS: + _pb_circuit_until = time.time() + _PB_CIRCUIT_COOLDOWN_SEC + _pb_fail_count = 0 + + async def _client() -> httpx.AsyncClient: return httpx.AsyncClient( base_url=settings.pb_url.rstrip("/"), - timeout=20.0, + timeout=_PB_TIMEOUT_SEC, trust_env=False, ) @@ -34,39 +57,58 @@ async def _client() -> httpx.AsyncClient: async def ensure_admin() -> None: global _token, _token_expire async with await _client() as client: - try: - resp = await client.post( - "/api/collections/_superusers/auth-with-password", - json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password}, - ) - if resp.status_code == 200: - data = resp.json() - _token = data.get("token") or "" - _token_expire = time.time() + 3600 - return - except Exception: - pass + auth_paths = ( + "/api/collections/_superusers/auth-with-password", + "/api/admins/auth-with-password", + ) + for path in auth_paths: + try: + resp = await client.post( + path, + json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password}, + ) + if resp.status_code == 200: + data = resp.json() + _token = data.get("token") or "" + _token_expire = time.time() + 3600 + return + except Exception: + pass - try: - resp = await client.post( + create_attempts = ( + ( "/api/collections/_superusers/records", - json={ + { "email": settings.pb_admin_email, "password": settings.pb_admin_password, "passwordConfirm": settings.pb_admin_password, }, - ) - if resp.status_code in (200, 201): - login = await client.post( - "/api/collections/_superusers/auth-with-password", - json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password}, - ) - if login.status_code == 200: - _token = login.json().get("token") or "" - _token_expire = time.time() + 3600 - return - except Exception: - pass + ), + ( + "/api/admins", + { + "email": settings.pb_admin_email, + "password": settings.pb_admin_password, + "passwordConfirm": settings.pb_admin_password, + }, + ), + ) + for create_path, payload in create_attempts: + try: + resp = await client.post(create_path, json=payload) + if resp.status_code not in (200, 201): + continue + for path in auth_paths: + login = await client.post( + path, + json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password}, + ) + if login.status_code == 200: + _token = login.json().get("token") or "" + _token_expire = time.time() + 3600 + return + except Exception: + pass # keep previous token only if still valid; otherwise clear if time.time() > _token_expire: _token = "" @@ -253,62 +295,75 @@ async def ensure_collections() -> dict[str, Any]: async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]: - headers = await _auth_headers() - if not headers: - headers = await _auth_headers(force=True) - if not headers: + if _pb_circuit_open(): return None - async with await _client() as client: - filt = f'sqlite_id="{sqlite_id}"' - found = await client.get( - f"/api/collections/{collection}/records", - headers=headers, - params={"filter": filt, "perPage": 1}, - ) - if found.status_code == 401: + try: + headers = await _auth_headers() + if not headers: headers = await _auth_headers(force=True) - if not headers: - return None + if not headers: + _pb_note_failure() + return None + async with await _client() as client: + filt = f'sqlite_id="{sqlite_id}"' found = await client.get( f"/api/collections/{collection}/records", headers=headers, params={"filter": filt, "perPage": 1}, ) - body = {**data, "sqlite_id": sqlite_id} - if found.status_code == 200 and (found.json().get("items") or []): - rid = found.json()["items"][0]["id"] - resp = await client.patch( - f"/api/collections/{collection}/records/{rid}", + if found.status_code == 401: + headers = await _auth_headers(force=True) + if not headers: + _pb_note_failure() + return None + found = await client.get( + f"/api/collections/{collection}/records", + headers=headers, + params={"filter": filt, "perPage": 1}, + ) + body = {**data, "sqlite_id": sqlite_id} + if found.status_code == 200 and (found.json().get("items") or []): + rid = found.json()["items"][0]["id"] + resp = await client.patch( + f"/api/collections/{collection}/records/{rid}", + headers=headers, + json=body, + ) + if resp.status_code in (200, 204): + _pb_note_success() + return rid + _pb_note_failure() + return None + # PocketBase text PK collections require explicit id on create + body["id"] = _pb_id(sqlite_id) + resp = await client.post( + f"/api/collections/{collection}/records", headers=headers, json=body, ) - if resp.status_code in (200, 204): - return rid - return None - # PocketBase text PK collections require explicit id on create - body["id"] = _pb_id(sqlite_id) - resp = await client.post( - f"/api/collections/{collection}/records", - headers=headers, - json=body, - ) - if resp.status_code in (200, 201): - return resp.json().get("id") or body["id"] - # conflict: try fetch again / patch - if resp.status_code in (400, 409): - found2 = await client.get( - f"/api/collections/{collection}/records", - headers=headers, - params={"filter": filt, "perPage": 1}, - ) - if found2.status_code == 200 and (found2.json().get("items") or []): - rid = found2.json()["items"][0]["id"] - await client.patch( - f"/api/collections/{collection}/records/{rid}", + if resp.status_code in (200, 201): + _pb_note_success() + return resp.json().get("id") or body["id"] + # conflict: try fetch again / patch + if resp.status_code in (400, 409): + found2 = await client.get( + f"/api/collections/{collection}/records", headers=headers, - json={k: v for k, v in body.items() if k != "id"}, + params={"filter": filt, "perPage": 1}, ) - return rid + if found2.status_code == 200 and (found2.json().get("items") or []): + rid = found2.json()["items"][0]["id"] + await client.patch( + f"/api/collections/{collection}/records/{rid}", + headers=headers, + json={k: v for k, v in body.items() if k != "id"}, + ) + _pb_note_success() + return rid + _pb_note_failure() + return None + except Exception: + _pb_note_failure() return None @@ -479,7 +534,11 @@ async def delete_channel_group(sqlite_id: str) -> bool: async def health() -> dict[str, Any]: try: - async with await _client() as client: + async with httpx.AsyncClient( + base_url=settings.pb_url.rstrip("/"), + timeout=1.0, + trust_env=False, + ) as client: resp = await client.get("/api/health") ok = resp.status_code == 200 body: Any diff --git a/backend/app/s3_storage.py b/backend/app/s3_storage.py index b2f80b4..bce079d 100644 --- a/backend/app/s3_storage.py +++ b/backend/app/s3_storage.py @@ -3,6 +3,7 @@ from __future__ import annotations import mimetypes +import time from pathlib import Path from typing import Any, Optional from urllib.parse import quote @@ -120,6 +121,86 @@ def delete_object(key: str) -> bool: return False +def purge_covers_older_than(*, keep_days: float = 2.0, max_delete: int = 5000) -> dict[str, Any]: + """Delete session cover objects older than keep_days. + + Scope: ``covers/*.jpg`` session frames only — never touches ``covers/avatars/``. + Permanent project policy: keep at most ~2 days of cover blobs in Seaweed/S3. + """ + out: dict[str, Any] = { + "ok": False, + "enabled": s3_enabled(), + "keep_days": float(keep_days), + "listed": 0, + "deleted": 0, + "skipped_avatar": 0, + "skipped_fresh": 0, + "errors": 0, + "bytes_deleted": 0, + } + if not s3_enabled(): + return out + try: + days = max(0.5, min(30.0, float(keep_days))) + except Exception: + days = 2.0 + out["keep_days"] = days + cutoff = time.time() - days * 86400.0 + limit = max(1, min(20000, int(max_delete))) + client = _client() + bucket = settings.s3_bucket + token: str | None = None + try: + while out["deleted"] < limit: + kwargs: dict[str, Any] = { + "Bucket": bucket, + "Prefix": "covers/", + "MaxKeys": 1000, + } + if token: + kwargs["ContinuationToken"] = token + resp = client.list_objects_v2(**kwargs) + contents = resp.get("Contents") or [] + if not contents and not resp.get("IsTruncated"): + break + for obj in contents: + key = str(obj.get("Key") or "") + if not key or key.endswith("/"): + continue + out["listed"] += 1 + # stable room avatars — not session covers + if key.startswith("covers/avatars/"): + out["skipped_avatar"] += 1 + continue + lm = obj.get("LastModified") + try: + ts = float(lm.timestamp()) if lm is not None else 0.0 + except Exception: + ts = 0.0 + if ts >= cutoff: + out["skipped_fresh"] += 1 + continue + try: + client.delete_object(Bucket=bucket, Key=key) + out["deleted"] += 1 + out["bytes_deleted"] += int(obj.get("Size") or 0) + except Exception: + out["errors"] += 1 + if out["deleted"] >= limit: + break + if out["deleted"] >= limit: + break + if not resp.get("IsTruncated"): + break + token = resp.get("NextContinuationToken") + if not token: + break + out["ok"] = True + except Exception as exc: + out["error"] = str(exc)[:240] + return out + + def upload_cover(session_id: str, local_path: str | Path) -> str: key = f"covers/{session_id}.jpg" return upload_file(local_path, key, content_type="image/jpeg") diff --git a/backend/app/session_auth.py b/backend/app/session_auth.py index 34a0fde..0a0721e 100644 --- a/backend/app/session_auth.py +++ b/backend/app/session_auth.py @@ -27,6 +27,7 @@ _PUBLIC_API_PREFIXES = ( ) _PUBLIC_API_EXACT = { "/api/health", + "/api/ping", "/api/shorts/oauth/callback", "/api/tiktok/oauth/callback/", "/api/tiktok/oauth/callback", @@ -204,12 +205,9 @@ class SessionAuthMiddleware: if method in {"GET", "HEAD"} and path.startswith("/api/sessions/") and path.endswith("/cover"): await self.app(scope, receive, send) return + # Static cover files — allow without cookie (same as /api/sessions/.../cover). if path.startswith("/covers/"): - if session_user_from_request(request): - await self.app(scope, receive, send) - return - resp = JSONResponse({"detail": "未登录"}, status_code=401) - await resp(scope, receive, send) + await self.app(scope, receive, send) return if not path.startswith("/api/"): diff --git a/backend/app/shellcrash_hub.py b/backend/app/shellcrash_hub.py index 95692af..10f5c45 100644 --- a/backend/app/shellcrash_hub.py +++ b/backend/app/shellcrash_hub.py @@ -15,22 +15,52 @@ from pathlib import Path from typing import Any CONTROLLER = "http://127.0.0.1:9999" -DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_hysteria5") +# Physical YouTube Live egress: TUIC only (hy2 often dead). Auto-pick must NEVER +# prefer VLESS — VLESS IP changes trigger YouTube Live channel verification popups. +DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_tuic5") DEFAULT_PROFILE = os.environ.get("DY_SHELLCRASH_DEFAULT_PROFILE", "config.yaml") +ALLOW_VLESS_AUTOPICK = str(os.environ.get("DY_SHELLCRASH_ALLOW_VLESS", "") or "").strip().lower() in { + "1", + "true", + "yes", + "on", +} +# Order = preference for pick_best_node (TUIC → hy2/hysteria → optional VLESS). CANDIDATE_NODES = ( - "1d2da142-singbox_hysteria5", "1d2da142-singbox_tuic5", - "1d2da142-VLESS_Reality_Vision5", - "e3ea3b30-singbox_hysteria_vultr", "e3ea3b30-singbox_tuic_vultr", - "242af835-singbox_hysteria", "hackrobot-singbox_tuic", + "1d2da142-singbox_hysteria5", + "e3ea3b30-singbox_hysteria_vultr", + "242af835-singbox_hysteria", + "1d2da142-VLESS_Reality_Vision5", + "e3ea3b30-VLESS_Reality_Vision_vultr", "VLESS_Reality_Vision", + "VLESS_Reality_Vision2", "socks5", "proxycheap", ) SELECT_GROUPS = ("GLOBAL", "🚀 节点选择") + +def _node_family(name: str) -> str: + u = str(name or "").upper() + if "TUIC" in u: + return "tuic" + if "HYSTERIA" in u or "HY2" in u or "SINGBOX_HYSTERIA" in u: + return "hy2" + if "VLESS" in u: + return "vless" + return "other" + + +def _family_rank(family: str) -> int: + """Lower = preferred for auto-pick.""" + order = {"tuic": 0, "hy2": 1, "other": 2, "vless": 9} + if family == "vless" and not ALLOW_VLESS_AUTOPICK: + return 100 # effectively excluded + return order.get(family, 2) + MANAGED_ROOTS: dict[str, tuple[str, str]] = { "shellcrash-yamls": ("yamls", "YAML 配置"), "shellcrash-configs": ("configs", "配置文件"), @@ -292,6 +322,11 @@ def apply_profile(rel_path: str | None = None, target_node: str | None = None) - """SH2-compatible: stage YAML → config.yaml → restart → select node.""" rel = (rel_path or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE node = (target_node or DEFAULT_NODE).strip() or DEFAULT_NODE + blocked_vless = False + if _node_family(node) == "vless" and not ALLOW_VLESS_AUTOPICK: + # Physical Live: never land on VLESS via apply_profile (YouTube channel verify). + node = DEFAULT_NODE + blocked_vless = True yamls = shellcrash_dir() / "yamls" yamls.mkdir(parents=True, exist_ok=True) source = _safe_rel(yamls, rel) @@ -327,6 +362,7 @@ def apply_profile(rel_path: str | None = None, target_node: str | None = None) - "path": rel, "target_node": node, "selected": st.get("selected_node") or node, + "blocked_vless": blocked_vless, "applied_groups": applied, "command_ok": bool(run.get("ok")), "shellcrash": st, @@ -498,23 +534,64 @@ def probe_mixed(*, timeout: float = 10.0) -> dict[str, Any]: def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]: + """Pick a working egress node with TUIC > hy2 preference. + + Never auto-selects VLESS unless DY_SHELLCRASH_ALLOW_VLESS=1 — VLESS egress + has triggered YouTube Live verification on all physical channels. + Does not change business DB/settings; only Clash selector now-node. + """ listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0) if not listed.get("ok"): return {"ok": False, "error": listed.get("error") or "controller unreachable", "picked": None} proxies = (listed.get("data") or {}).get("proxies") or {} + + # Sticky: if current selector is already an allowed healthy family, keep it. + current = None + try: + current = (proxies.get("🚀 节点选择") or {}).get("now") or (proxies.get("GLOBAL") or {}).get("now") + except Exception: + current = None + if current and _family_rank(_node_family(current)) < 100: + enc = urllib.parse.quote(str(current), safe="") + url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204" + res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0) + delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0 + if delay > 0: + egress = probe_mixed() + if egress.get("ok"): + return { + "ok": True, + "picked": current, + "delay_ms": delay, + "sticky": True, + "family": _node_family(str(current)), + "delays": [{"name": current, "delay": delay, "ok": True}], + "applied": [], + "egress": egress, + } + delays: list[dict[str, Any]] = [] best_name: str | None = None - best_delay = 10**9 + best_key: tuple[int, int] | None = None # (family_rank, delay) for name in CANDIDATE_NODES: if name not in proxies: continue + fam = _node_family(name) + rank = _family_rank(fam) + if rank >= 100: + delays.append({"name": name, "delay": 0, "ok": False, "skipped": "vless_blocked"}) + continue enc = urllib.parse.quote(name, safe="") url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204" res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0) delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0 - delays.append({"name": name, "delay": delay, "ok": delay > 0}) - if delay > 0 and delay < best_delay: - best_name, best_delay = name, delay + delays.append({"name": name, "delay": delay, "ok": delay > 0, "family": fam}) + if delay <= 0: + continue + key = (rank, delay) + if best_key is None or key < best_key: + best_key = key + best_name = name applied: list[dict[str, Any]] = [] if best_name: applied = _select_node_in_groups(best_name) @@ -522,14 +599,30 @@ def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]: return { "ok": bool(best_name) and bool(egress.get("ok")), "picked": best_name, - "delay_ms": best_delay if best_name else None, + "delay_ms": (best_key[1] if best_key else None), + "family": _node_family(best_name) if best_name else None, + "allow_vless": ALLOW_VLESS_AUTOPICK, "delays": delays, "applied": applied, "egress": egress, } -def status() -> dict[str, Any]: +_STATUS_CACHE: dict[str, Any] = {"at": 0.0, "payload": None} +_STATUS_CACHE_TTL = float(os.environ.get("DY_SHELLCRASH_STATUS_TTL", "5") or "5") + + +def status(*, force: bool = False) -> dict[str, Any]: + """ShellCrash status — short TTL cache (network page used to call this 3–4×/request).""" + now = time.time() + cached = _STATUS_CACHE.get("payload") + if ( + not force + and isinstance(cached, dict) + and now - float(_STATUS_CACHE.get("at") or 0) < _STATUS_CACHE_TTL + ): + return dict(cached) + cfg_vals = _read_cfg() yaml = _config_yaml() unit_name = "shellcrash.service" @@ -546,7 +639,7 @@ def status() -> dict[str, Any]: if prox.get("ok"): pdata = (prox.get("data") or {}).get("proxies") or {} selected = (pdata.get("🚀 节点选择") or {}).get("now") or (pdata.get("GLOBAL") or {}).get("now") - return { + out = { "ok": True, "available": yaml.get("available") or start_sh.is_file() or unit_active == "active", "installed": start_sh.is_file() or _unit_exists(unit_name), @@ -559,12 +652,18 @@ def status() -> dict[str, Any]: "status": "online" if running else ("configured" if start_sh.is_file() or _unit_exists(unit_name) else "missing"), "mixed_port": mixed, "selected_node": selected, + "selected_family": _node_family(str(selected or "")), "default_node": DEFAULT_NODE, + "default_family": _node_family(DEFAULT_NODE), + "allow_vless_autopick": ALLOW_VLESS_AUTOPICK, "default_profile": DEFAULT_PROFILE, "config": yaml, "roots": managed_roots(), "hint": "应用配置会写入 config.yaml 并重启;web 面板打开 mihomo UI。", } + _STATUS_CACHE["at"] = now + _STATUS_CACHE["payload"] = out + return dict(out) def action(act: str) -> dict[str, Any]: @@ -601,11 +700,15 @@ def action(act: str) -> dict[str, Any]: picked = None if act in {"start", "restart"}: time.sleep(1.0) - # Prefer configured default node first, then pick if needed + # Prefer configured default (TUIC). Only auto-pick among non-VLESS if default fails. _select_node_in_groups(DEFAULT_NODE) egress = probe_mixed(timeout=6.0) if not egress.get("ok"): picked = pick_best_node() + # Never leave a restart on VLESS unless explicitly allowed. + if picked.get("picked") and _node_family(str(picked.get("picked"))) == "vless" and not ALLOW_VLESS_AUTOPICK: + _select_node_in_groups(DEFAULT_NODE) + picked = {**picked, "ok": False, "blocked_vless": True, "reverted_to": DEFAULT_NODE} st = status() ok = bool(st.get("running")) if act in {"start", "restart"} else (not st.get("running") if act == "stop" else True) return { diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 63d7de7..bcd776b 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -2,10 +2,17 @@ """Isolated Shorts pipeline — optional side path, never blocks Douyin monitor. Enable only via settings.shorts_enabled=True. + +Live-clip upload rules: +1. Different channels MAY share one Douyin live room; each gets a distinct + clip_offset window (0–15s / 15–30s / …) so materials are never identical. +2. Same channel cannot reuse the same room twice per Beijing day. +3. Same channel uploads spaced >10 minutes (hard floor). +4. Within Beijing calendar day, aggressively fill until daily_min is met. + - On-live edge enqueue (optional) - Random sample from currently-live rooms (default on) -Same room is only used once per Beijing day per channel pool. -All public entrypoints swallow exceptions so callers (monitor) stay safe. +- Quota fill toward daily_min first, then daily_max """ from __future__ import annotations @@ -20,9 +27,9 @@ from .shorts_upload import is_upload_quota_error, quota_error_message, upload_sh from .shorts_socks import resolve_upload_socks_proxy from .shorts_yt_quota import ( any_profile_uploads_available, + blocked_profile_ids, clear_all_upload_self_blocks, clear_stale_quota_errors_for_open_profiles, - pause_uploads_until_reset, profile_id_for_channel, profile_id_for_job, quota_budgets_by_profile, @@ -30,7 +37,8 @@ from .shorts_yt_quota import ( yt_upload_budget, ) from .timeutil import push_date_from_ts - +from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota +from .shorts_schedule import CHANNEL_GAP_FLOOR_SEC def _room_tags(room: dict[str, Any]) -> list[str]: tags = room.get("tags") or [] @@ -52,6 +60,112 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: return tag in tags or "shorts" in tags or "both" in tags +def _is_offline_stream_error(err: str) -> bool: + e = str(err or "") + low = e.lower() + if "无法获取直播流" in e or "已停播" in e: + return True + if "probe 404" in low or "server returned 404" in low: + return True + if "connection timed out" in low and ("opening input" in low or "http" in low): + return True + return False + + +def _live_room_map() -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + try: + for r in db.list_live_douyin_rooms_for_shorts(limit=500): + rid = str(r.get("room_id") or "").strip() + if rid: + out[rid] = r + except Exception: + return {} + return out + + +def _try_rebind_shorts_job_to_live(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> bool: + """If job's room is offline, point it at another live room for the same channel.""" + jid = str(job.get("id") or "") + ch_id = str(job.get("channel_pk") or "") + day = str(job.get("push_date") or push_date_from_ts(time.time())) + old_rid = str(job.get("room_id") or "") + if not jid or not ch_id: + return False + live = _live_room_map() + if old_rid and old_rid in live: + return False + settings = cfg or db.get_settings_map() + clip_sec = int(settings.get("shorts_clip_sec") or 15) + for room in live.values(): + new_rid = str(room.get("room_id") or "") + if not new_rid or new_rid == old_rid: + continue + if db.has_shorts_job_for_room_day(new_rid, day, ch_id): + continue + try: + clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts") + except Exception: + pass + offset = db.next_shorts_room_clip_offset(new_rid, day, clip_sec=clip_sec) + sid = str(room.get("active_session_id") or "") + session = db.get_session(sid) if sid else None + db.update_shorts_job( + jid, + status="pending", + room_id=new_rid, + room_pk=str(room.get("id") or ""), + session_id=sid, + source_url=str((session or {}).get("source_url") or room.get("url") or ""), + anchor_name=str( + (session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or "" + ), + stream_url="", + clip_path="", + clip_seconds=0, + clip_offset_sec=offset, + error="原直播间已停播,已换源重录", + finished_at=0, + upload_at=0, + youtube_video_id="", + youtube_url="", + ) + return True + return False + + +def _skip_offline_shorts_job(job: dict[str, Any], *, reason: str = "直播间已停播,已释放当日名额") -> None: + db.update_shorts_job( + str(job["id"]), + status="skipped", + error=reason, + stream_url="", + clip_path="", + finished_at=time.time(), + upload_at=0, + ) + + +def skip_or_rebind_offline_pending(cfg: dict[str, Any] | None = None, *, limit: int = 40) -> dict[str, int]: + """Pending jobs whose rooms left live map → rebind or skip (free pipeline).""" + settings = cfg or db.get_settings_map() + day = push_date_from_ts(time.time()) + live = _live_room_map() + data = db.list_shorts_jobs(push_date=day, status="pending", limit=max(1, min(limit, 120)), offset=0) + rebound = 0 + skipped = 0 + for job in data.get("jobs") or []: + rid = str(job.get("room_id") or "") + if rid and rid in live: + continue + if _try_rebind_shorts_job_to_live(job, settings): + rebound += 1 + else: + _skip_offline_shorts_job(job) + skipped += 1 + return {"rebound": rebound, "skipped": skipped} + + def _enqueue_job( *, session: dict[str, Any] | None, @@ -72,8 +186,10 @@ def _enqueue_job( if room_id.startswith("yt:"): return None day = str(push_date or "").strip() or push_date_from_ts(time.time()) - # Global dedup: same room_id can only be enqueued ONCE per Beijing day across ALL channels - if settings.get("shorts_dedupe_room_day", True) and room_id: + # Legacy global room-day lock (off by default). Prefer channel-scoped uniqueness + # so multiple channels can share one live room with distinct clip offsets. + dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) + if dedupe_global and room_id: if db.has_shorts_job_for_room_day(room_id, day): return None channel: dict[str, Any] | None = None @@ -81,13 +197,29 @@ def _enqueue_job( ch = db.get_shorts_channel(channel_pk) if ch and ch.get("enabled"): used = db.shorts_channel_upload_count(channel_pk, day) - daily_max = db.SHORTS_DAILY_FORCE - if used < daily_max: + uploaded = db.shorts_channel_uploaded_count(channel_pk, day) + daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) + daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE) + if daily_max < daily_min: + daily_max = daily_min + if used < daily_max and uploaded < daily_max: channel = ch if not channel: channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota) if require_channel and not channel: return None + # Same channel + same room today → skip (create_shorts_job also enforces). + ch_id = str((channel or {}).get("id") or "") + if room_id and ch_id and not dedupe_global and db.has_shorts_job_for_room_day(room_id, day, ch_id): + return None + clip_sec = int(settings.get("shorts_clip_sec") or 15) + try: + clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts") + except Exception: + pass + offset = 0 + if room_id and not dedupe_global: + offset = db.next_shorts_room_clip_offset(room_id, day, clip_sec=clip_sec) sid = str((session or {}).get("id") or room.get("active_session_id") or "") job = db.create_shorts_job( session_id=sid, @@ -98,8 +230,10 @@ def _enqueue_job( (session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or "" ), stream_url=str(stream_url or ""), - channel_pk=str((channel or {}).get("id") or ""), + channel_pk=ch_id, push_date=day, + clip_offset_sec=offset, + dedupe_room_global=dedupe_global, ) if not job: return None @@ -140,7 +274,8 @@ def try_enqueue_on_live( def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: - """Pick random currently-live rooms and enqueue (dedupe room/day). Returns enqueued count.""" + """Pick currently-live rooms and enqueue. Same room may feed multiple channels + with distinct clip offsets unless shorts_dedupe_room_day is on.""" try: settings = cfg or db.get_settings_map() if not settings.get("shorts_enabled"): @@ -152,7 +287,8 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: return 0 batch = max(1, min(int(settings.get("shorts_live_sample_batch") or 1), 5)) any_live = settings.get("shorts_sample_any_live", True) - used = db.room_ids_with_shorts_job_today(day) + dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) + used = db.room_ids_with_shorts_job_today(day) if dedupe_global else set() rooms = db.list_live_douyin_rooms_for_shorts(limit=400) candidates: list[dict[str, Any]] = [] for room in rooms: @@ -165,16 +301,27 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: candidates.append(room) if not candidates: return 0 - random.shuffle(candidates) + # Prefer rooms with fewer Shorts jobs today (still allow reuse when not global-dedupe). + if not dedupe_global: + candidates.sort( + key=lambda r: db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day) + and 1 + or 0 + ) + random.shuffle(candidates) + else: + random.shuffle(candidates) enqueued = 0 - for room in candidates[:batch]: + for room in candidates[: max(batch * 3, batch)]: + if enqueued >= batch: + break sid = str(room.get("active_session_id") or "") session = db.get_session(sid) if sid else None job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings) if job: enqueued += 1 - used.add(str(room.get("room_id") or "")) - # stop if channel full after this assign + if dedupe_global: + used.add(str(room.get("room_id") or "")) if not db.pick_shorts_channel(day, settings): break return enqueued @@ -210,7 +357,7 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: continue if not any_live and not _room_eligible(room, settings): continue - if settings.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(rid, day): + if settings.get("shorts_dedupe_room_day", False) and db.has_shorts_job_for_room_day(rid, day): skipped += 1 continue unused.append(room) @@ -245,7 +392,12 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: - """Enqueue live-room clips toward each channel's daily_max before Beijing midnight.""" + """Enqueue live-room clips toward daily_min first, then daily_max (Beijing day). + + Same live room may be shared across channels; each job gets a distinct clip_offset + (0–15s / 15–30s / …) so materials are never identical. Prefer rooms with fewer + jobs today for diversity. When behind daily_min, raise batch size. + """ try: settings = cfg or db.get_settings_map() if not settings.get("shorts_enabled"): @@ -253,8 +405,10 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: if not any_profile_uploads_available(settings): return 0 day = push_date_from_ts(time.time()) - gap_total = db.shorts_total_quota_gap(day) - if gap_total <= 0: + summary = db.shorts_channels_quota_summary(day) + under_min = [r for r in summary if not r.get("min_met") and int(r.get("gap") or 0) > 0] + need_any = [r for r in summary if int(r.get("gap") or 0) > 0] + if not need_any: return 0 if not db.pick_shorts_channel(day, settings): return 0 @@ -264,21 +418,27 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: day_start, day_end = beijing_day_bounds(day) now = time.time() day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start))) + gap_total = sum(int(r.get("gap") or 0) for r in need_any) + min_gap = sum(max(0, int(r.get("daily_min") or 0) - int(r.get("used") or 0)) for r in under_min) + base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 9)) - if day_progress > 0.55: - base_batch = max(base_batch, min(gap_total, 6)) - if day_progress > 0.75: - base_batch = max(base_batch, min(gap_total, 10)) - if day_progress > 0.88: - base_batch = max(base_batch, min(gap_total, 16)) + if under_min: + base_batch = max(base_batch, min(max(min_gap, len(under_min)), 12)) + if day_progress > 0.45 and under_min: + base_batch = max(base_batch, min(gap_total, max(8, min_gap))) + if day_progress > 0.7: + base_batch = max(base_batch, min(gap_total, 14)) + if day_progress > 0.85 or (day_progress > 0.6 and under_min): + base_batch = max(base_batch, min(gap_total, 20)) any_live = settings.get("shorts_sample_any_live", True) - used = db.room_ids_with_shorts_job_today(day) + dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) + used_rooms = db.room_ids_with_shorts_job_today(day) if dedupe_global else set() rooms = db.list_live_douyin_rooms_for_shorts(limit=400) candidates: list[dict[str, Any]] = [] for room in rooms: rid = str(room.get("room_id") or "") - if not rid or rid in used: + if not rid or rid in used_rooms: continue if not any_live and not _room_eligible(room, settings): continue @@ -286,20 +446,71 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: candidates.append(room) if not candidates: return 0 - random.shuffle(candidates) + # Prefer less-used rooms first, then shuffle within similar load. + if not dedupe_global: + candidates.sort( + key=lambda r: ( + 1 if db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day) else 0, + random.random(), + ) + ) + else: + random.shuffle(candidates) + + target_ids = [str(r["id"]) for r in under_min] + [ + str(r["id"]) for r in need_any if r.get("min_met") + ] + if not target_ids: + return 0 enqueued = 0 - for room in candidates: - if enqueued >= base_batch: - break - if not db.pick_shorts_channel(day, settings): - break - sid = str(room.get("active_session_id") or "") - session = db.get_session(sid) if sid else None - job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings) - if job: - enqueued += 1 - used.add(str(room.get("room_id") or "")) + ti = 0 + # Allow cycling the same live rooms across channels (distinct offsets). + room_cycle = list(candidates) + if not room_cycle: + return 0 + attempts = 0 + max_attempts = max(base_batch * 4, len(target_ids) * 2) + while enqueued < base_batch and attempts < max_attempts: + attempts += 1 + room = room_cycle[(attempts - 1) % len(room_cycle)] + rid = str(room.get("room_id") or "") + assigned = False + for _ in range(len(target_ids)): + tid = target_ids[ti % len(target_ids)] + ti += 1 + ch = db.get_shorts_channel(tid) + if not ch or not ch.get("enabled"): + continue + used = db.shorts_channel_upload_count(tid, day) + uploaded = db.shorts_channel_uploaded_count(tid, day) + daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) + if used >= daily_max or uploaded >= daily_max: + continue + if rid and db.has_shorts_job_for_room_day(rid, day, tid): + continue + from .shorts_yt_quota import profile_id_for_channel, project_uploads_available + + if not project_uploads_available(settings, profile_id=profile_id_for_channel(ch)): + continue + sid = str(room.get("active_session_id") or "") + session = db.get_session(sid) if sid else None + job = _enqueue_job( + session=session, + room=room, + stream_url="", + cfg=settings, + channel_pk=tid, + ) + if job: + enqueued += 1 + if dedupe_global: + used_rooms.add(rid) + assigned = True + break + if not assigned and dedupe_global: + # Exhausted unique rooms under legacy mode. + continue return enqueued except Exception: return 0 @@ -460,16 +671,41 @@ class ShortsPipeline: continue return n + @staticmethod + def _end_of_day_catchup(cfg: dict[str, Any] | None = None) -> bool: + try: + from .shorts_schedule import fleet_pace_plan + + plan = fleet_pace_plan(cfg=cfg) + if plan.get("behind") or plan.get("urgent"): + return True + from .timeutil import beijing_day_bounds + + day = push_date_from_ts(time.time()) + _, day_end = beijing_day_bounds(day) + if day_end - time.time() > 2400: + return False + return db.shorts_total_quota_gap(day) > 0 + except Exception: + return False + @staticmethod def _upload_max(cfg: dict[str, Any]) -> int: explicit = int(cfg.get("shorts_upload_max_concurrent") or 0) if explicit > 0: - return max(1, min(explicit, 5)) - return max(2, int(cfg.get("shorts_max_concurrent") or 1)) + base = max(1, min(explicit, 5)) + else: + base = max(2, int(cfg.get("shorts_max_concurrent") or 1)) + if ShortsPipeline._end_of_day_catchup(cfg): + return min(5, max(base, 4)) + return base @staticmethod def _record_max(cfg: dict[str, Any]) -> int: - return max(1, int(cfg.get("shorts_max_concurrent") or 1)) + base = max(1, int(cfg.get("shorts_max_concurrent") or 1)) + if ShortsPipeline._end_of_day_catchup(cfg): + return min(8, max(base, 5)) + return base def status(self) -> dict[str, Any]: now = time.time() @@ -530,6 +766,8 @@ class ShortsPipeline: yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A") yt_by_profile = quota_budgets_by_profile(cfg) exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")] + cool_profiles = [r for r in yt_by_profile if r.get("blocked")] + cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0) try: from . import douyin_live @@ -564,12 +802,18 @@ class ShortsPipeline: "auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)), "quota_gap": db.shorts_total_quota_gap(), "quota_defaults": db.shorts_quota_defaults(cfg), - # Informational only — never gates manual/worker uploads - "upload_quota_blocked": False, - "upload_quota_blocked_until": 0, - "upload_quota_blocked_profiles": [], + # API cool-down only (real YouTube 429) — manual upload never gated + "upload_quota_blocked": bool(cool_profiles), + "upload_quota_blocked_until": cool_until, + "upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_profiles], "yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted], - "yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0), + "yt_quota_reset_at": max( + (float(r.get("reset_at") or 0) for r in exhausted), + default=0, + ), + "yt_quota_cooldown_sec": int( + float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600) + ), "yt_upload_limit": yt_limit, "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, @@ -581,8 +825,8 @@ class ShortsPipeline: "douyin_live_count": live_count, "douyin_live_rooms": live_rooms, "upload_spread": bool(cfg.get("shorts_upload_spread", True)), - "upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or 720), - "channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400), + "upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC), + "channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC), "max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)), "upload_max_concurrent": self._upload_max(cfg), "delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)), @@ -594,6 +838,20 @@ class ShortsPipeline: "heatmap": heatmap, "oauth_issues": oauth_issues, } + try: + from .shorts_schedule import fleet_pace_plan + + pace = fleet_pace_plan(cfg=cfg) + payload["pace"] = pace + if pace.get("behind") or pace.get("urgent"): + payload["upload_min_gap_sec"] = float( + pace.get("recommended_global_gap_sec") or payload["upload_min_gap_sec"] + ) + payload["channel_min_gap_sec"] = float( + pace.get("recommended_channel_gap_sec") or payload["channel_min_gap_sec"] + ) + except Exception: + pass self._status_cache = payload self._status_cache_at = time.time() return payload @@ -640,6 +898,8 @@ class ShortsPipeline: yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A") yt_by_profile = quota_budgets_by_profile(cfg) exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")] + cool_profiles = [r for r in yt_by_profile if r.get("blocked")] + cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0) payload = { "running": bool(self._task and not self._task.done()), "busy": self._active_records > 0 or self._active_uploads > 0, @@ -652,9 +912,12 @@ class ShortsPipeline: "quota_filled": self.quota_filled, "auto_retried": self.auto_retried, "quota_gap": db.shorts_total_quota_gap(), - "upload_quota_blocked": False, + "upload_quota_blocked": bool(cool_profiles), + "upload_quota_blocked_until": cool_until, + "upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_profiles], "yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted], "yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0), + "yt_quota_cooldown_sec": int(float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600)), "yt_upload_limit": yt_limit, "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, @@ -744,6 +1007,20 @@ class ShortsPipeline: quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120) quota_interval = max(60.0, quota_interval) + try: + day_now = push_date_from_ts(time.time()) + under = [r for r in db.shorts_channels_quota_summary(day_now) if not r.get("min_met")] + if under: + # Behind daily_min: fill more often so Beijing-day minimum is reachable. + quota_interval = min(quota_interval, 60.0) + from .timeutil import beijing_day_bounds + + ds, de = beijing_day_bounds(day_now) + prog = max(0.0, min(1.0, (time.time() - ds) / max(1.0, de - ds))) + if prog > 0.7: + quota_interval = 45.0 + except Exception: + pass if (time.time() - self._last_quota_fill_at) >= quota_interval: self._last_quota_fill_at = time.time() qn = try_fill_daily_quota(cfg) @@ -776,6 +1053,17 @@ class ShortsPipeline: self._backfill_schedules(cfg) except Exception: pass + try: + from .shorts_schedule import pull_forward_due_uploads + + if pull_forward_due_uploads(cfg): + pass + except Exception: + pass + try: + skip_or_rebind_offline_pending(cfg, limit=60) + except Exception: + pass try: n = db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0) @@ -803,8 +1091,9 @@ class ShortsPipeline: job: dict[str, Any] | None = None runner: str = "" if self._active_uploads < upload_max: - # Never skip profiles for local quota — YouTube API decides - job = db.claim_due_shorts_upload(skip_profile_ids=None) + # Skip Clients in YouTube-API cool-down (manual upload still allowed). + skip = blocked_profile_ids(cfg) + job = db.claim_due_shorts_upload(skip_profile_ids=skip or None) if job: runner = "upload" if not job and self._active_records < record_max: @@ -937,10 +1226,22 @@ class ShortsPipeline: pass def _record_quota_api_feedback(self, job: dict[str, Any], raw_error: str) -> None: - """Surface YouTube 429 on the job only — never self-pause the Client.""" + """On real YouTube 429: cool down this Client's auto-uploads; ntfy at most once per window.""" + from .shorts_yt_quota import defer_profile_shorts_uploads, mark_api_quota_cooldown + pid = profile_id_for_job(job) - # Keep local counter in sync for UI; do not set blocked_until / defer siblings - pause_uploads_until_reset(profile_id=pid, reason="") + until, should_notify = mark_api_quota_cooldown( + profile_id=pid, + reason=str(raw_error or "")[:160], + ) + try: + defer_profile_shorts_uploads( + pid, + until, + reason=f"Client {pid} 接口配额冷静至北京时间后重试", + ) + except Exception: + pass try: from . import yt_long_db @@ -950,7 +1251,6 @@ class ShortsPipeline: except Exception: pass friendly = quota_error_message(pid) - # Prefer raw API body when present so operators see the real interface reply api_snip = (raw_error or "").strip() if api_snip and api_snip != friendly: err_text = f"{friendly} | 接口:{api_snip[:280]}" @@ -965,13 +1265,22 @@ class ShortsPipeline: finished_at=time.time(), ) self.last_error = err_text[:300] - self._emit_shorts_event( - kind="shorts_quota", - level="warn", - message=f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传)", - job=job, - extra={"error": raw_error[:200], "oauth_profile_id": pid}, - ) + if should_notify: + left_min = max(1, int((until - time.time()) / 60)) + self._emit_shorts_event( + kind="shorts_quota", + level="warn", + message=( + f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传);" + f"自动上传冷静约 {left_min} 分钟后再试" + ), + job=job, + extra={ + "error": raw_error[:200], + "oauth_profile_id": pid, + "cool_until": until, + }, + ) def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool: """Return True if handled as YouTube quota API feedback (no local pause).""" @@ -1167,6 +1476,24 @@ class ShortsPipeline: async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None: jid = str(job["id"]) + # Shared clips disk with yt-long — refuse record when critically low (no setting change). + try: + from .clip_retention import disk_ok_for_record, purge_stale_clips + + ok_disk, free_gb = disk_ok_for_record(cfg) + if not ok_disk: + purge_stale_clips(cfg) + ok_disk, free_gb = disk_ok_for_record(cfg) + if not ok_disk: + db.update_shorts_job( + jid, + status="pending", + error=f"disk_low:{free_gb:.1f}GB", + started_at=0, + ) + return + except Exception: + pass # Isolated companion: enqueue 9:16 long-form master (never raises into Shorts). try: from .yt_long_pipeline import try_enqueue_from_shorts @@ -1184,6 +1511,14 @@ class ShortsPipeline: ) stream = candidates[0] if candidates else "" if not stream: + # Room already offline → rebind to another live source or free the slot. + if _try_rebind_shorts_job_to_live(job, cfg): + return + live = _live_room_map() + rid = str(job.get("room_id") or "") + if rid and rid not in live: + _skip_offline_shorts_job(job) + return err = str(job.get("error") or "") if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900: db.update_shorts_job( @@ -1193,19 +1528,8 @@ class ShortsPipeline: stream_url="", ) return - db.update_shorts_job( - jid, - status="failed", - error="无法获取直播流(可能已停播)", - finished_at=time.time(), - ) - self._emit_shorts_event( - kind="shorts_fail", - level="error", - message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — 无法获取直播流", - job=job, - extra={"error": "无法获取直播流(可能已停播)"}, - ) + # Still listed live but no playable URL — free slot, don't keep failing. + _skip_offline_shorts_job(job, reason="无法解析直播流,已释放当日名额") return sec = int(cfg.get("shorts_clip_sec") or 15) try: @@ -1220,10 +1544,34 @@ class ShortsPipeline: sec = db.room_clip_seconds(room, default=sec, platform="shorts") except Exception: pass + # Distinct live window relative to job create time: + # offset 0 → capture immediately; 15 → wait until t0+15s; 30 → t0+30s … + # So A/B/C from the same room never get the identical live segment. + try: + offset = max(0.0, float(job.get("clip_offset_sec") or 0)) + except (TypeError, ValueError): + offset = 0.0 + if offset > 0: + try: + created = float(job.get("created_at") or time.time()) + except (TypeError, ValueError): + created = time.time() + delay = max(0.0, (created + offset) - time.time()) + delay = min(delay, float(15 * 20)) + if delay > 0.5: + await asyncio.sleep(delay) outcome = await record_clip(job_id=jid, stream_urls=candidates, seconds=sec) stream = str(outcome.get("stream_url") or stream) if not outcome.get("ok"): err = str(outcome.get("error") or "录制失败") + if _is_offline_stream_error(err): + if _try_rebind_shorts_job_to_live(job, cfg): + return + live = _live_room_map() + rid = str(job.get("room_id") or "") + if not rid or rid not in live: + _skip_offline_shorts_job(job, reason=f"直播流失效已停播,已释放名额({err[:80]})") + return db.update_shorts_job( jid, status="failed", @@ -1236,7 +1584,7 @@ class ShortsPipeline: level="error", message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — {err[:80]}", job=job, - extra={"error": err}, + extra={"error": err[:200]}, ) return clip_path = str(outcome.get("path") or "") diff --git a/backend/app/shorts_schedule.py b/backend/app/shorts_schedule.py index fca30b6..90218bb 100644 --- a/backend/app/shorts_schedule.py +++ b/backend/app/shorts_schedule.py @@ -1,7 +1,17 @@ # -*- coding: utf-8 -*- -"""Irregular 24h upload scheduling — avoid dense / metronomic YouTube uploads.""" +"""Irregular upload scheduling — meet Beijing-day quota without metronomic spam. + +Operator rules (Shorts live clips): +1. One Douyin room material → at most one Shorts channel (room-day uniqueness per channel). +2. Same channel uploads spaced ≥10 minutes normally; may compress only when behind deadline pace. +3. Prefer distinct Douyin rooms toward each channel's daily quota. +4. Within Beijing calendar day, prioritize meeting daily_min before daily_max. +5. Progress / 已满 = successful uploads only (not pending/queued). +6. Pace target: finish ~90% of fleet daily_max by Beijing 20:00; remaining 10% may use 20–24h. +""" from __future__ import annotations +import math import random import time from typing import Any @@ -12,12 +22,119 @@ from . import db from . import youtube_manage from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts +# Normal floor: same-channel upload interval must be >10 minutes. +CHANNEL_GAP_FLOOR_SEC = 600.0 +GLOBAL_GAP_FLOOR_SEC = 300.0 +# Behind 20:00 front-load pace / day-end catch-up. +EMERGENCY_CHANNEL_GAP_SEC = 90.0 +EMERGENCY_GLOBAL_GAP_SEC = 45.0 + +# Finish this fraction of fleet daily_max by Beijing deadline hour. +QUOTA_DEADLINE_HOUR = 20 +QUOTA_FRONTLOAD_RATIO = 0.90 + def _day_end_ts(push_date: str) -> float: """Exclusive end of Beijing calendar day for push_date (next midnight).""" return beijing_day_bounds(push_date)[1] +def _deadline_ts(push_date: str) -> float: + """Beijing wall-clock target for front-loaded quota (default 20:00).""" + day_start, day_end = beijing_day_bounds(push_date) + return min(day_end - 30.0, day_start + float(QUOTA_DEADLINE_HOUR) * 3600.0) + + +def fleet_pace_plan( + push_date: str = "", + *, + now: float | None = None, + cfg: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Derive upload gaps from channel count + daily quotas vs Beijing 20:00 / 90% target.""" + settings = cfg or db.get_settings_map() + now_ts = float(now if now is not None else time.time()) + day = push_date or push_date_from_ts(now_ts) + day_start, day_end = beijing_day_bounds(day) + deadline = _deadline_ts(day) + summary = db.shorts_channels_quota_summary(day) + n_ch = max(1, len(summary)) + uploaded = sum(int(r.get("uploaded") or r.get("used") or 0) for r in summary) + target = sum(int(r.get("daily_max") or 0) for r in summary) + if target <= 0: + target = n_ch * 9 + front_target = max(1, int(math.ceil(float(QUOTA_FRONTLOAD_RATIO) * target))) + need_front = max(0, front_target - uploaded) + total_gap = sum(int(r.get("gap") or 0) for r in summary) + + before_deadline = now_ts < deadline + span_to_deadline = max(1.0, deadline - day_start) + if before_deadline: + progress = max(0.0, min(1.0, (now_ts - day_start) / span_to_deadline)) + time_left = max(60.0, deadline - now_ts) + else: + progress = 1.0 + time_left = max(60.0, day_end - now_ts) + + expected_by_now = int(front_target * progress) if before_deadline else front_target + behind = uploaded < expected_by_now and (need_front > 0 or total_gap > 0) + + # Ideal global spacing so remaining front-load fits before deadline (fleet-wide). + ideal_global = time_left / max(1, need_front or total_gap or 1) + # Ideal per-channel: each channel still needs ~front_ratio*daily_max - used + per_ch_need = [] + for r in summary: + dmax = max(1, int(r.get("daily_max") or 9)) + used = int(r.get("uploaded") or r.get("used") or 0) + per_ch_need.append(max(0, int(math.ceil(QUOTA_FRONTLOAD_RATIO * dmax)) - used)) + avg_ch_need = max(1, int(round(sum(per_ch_need) / max(1, len(per_ch_need))))) if per_ch_need else 1 + ideal_channel = time_left / max(1, avg_ch_need) + + configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + + # When behind: use computed gaps (still respect floors unless truly impossible). + if behind or (before_deadline and need_front > 0 and progress > 0.15): + global_gap = min(configured_global, max(EMERGENCY_GLOBAL_GAP_SEC, ideal_global * 0.92)) + channel_gap = min(configured_channel, max(CHANNEL_GAP_FLOOR_SEC, ideal_channel * 0.85)) + # If even 10min/channel cannot finish fleet front-load, allow compress later via urgent. + slots_at_floor = (time_left / CHANNEL_GAP_FLOOR_SEC) * n_ch + urgent = need_front > slots_at_floor * 0.92 or (not before_deadline and total_gap > 0) + if urgent: + # Parallel channels: wall-clock ≈ need/n_ch * gap + per_wall = time_left / max(1.0, math.ceil(need_front / max(1, n_ch))) + channel_gap = max(EMERGENCY_CHANNEL_GAP_SEC, min(channel_gap, per_wall * 0.9)) + global_gap = max(EMERGENCY_GLOBAL_GAP_SEC, min(global_gap, channel_gap * 0.75)) + else: + # Ahead of pace: keep configured gaps, lightly stretch so we don't dump everything early. + global_gap = max(GLOBAL_GAP_FLOOR_SEC, configured_global) + channel_gap = max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global) + urgent = False + + per_hour = (3600.0 / max(global_gap, 1.0)) if global_gap else 0.0 + return { + "push_date": day, + "n_channels": n_ch, + "uploaded": uploaded, + "target": target, + "front_target": front_target, + "need_front": need_front, + "total_gap": total_gap, + "deadline_hour": QUOTA_DEADLINE_HOUR, + "deadline_ts": deadline, + "before_deadline": before_deadline, + "deadline_progress": round(progress, 4), + "expected_by_now": expected_by_now, + "behind": behind, + "urgent": urgent, + "time_left_sec": time_left, + "recommended_global_gap_sec": round(global_gap, 1), + "recommended_channel_gap_sec": round(channel_gap, 1), + "recommended_per_hour": round(per_hour, 2), + "frontload_ratio": QUOTA_FRONTLOAD_RATIO, + } + + def _occupied_slots(push_date: str) -> list[tuple[float, str]]: """(upload_at_or_finished, channel_pk) for jobs that already claim a slot today.""" data = db.list_shorts_jobs(push_date=push_date, limit=500, offset=0) @@ -42,37 +159,71 @@ def _quota_pressure( push_date: str, now: float, ) -> tuple[float, float, bool, bool]: - """Return (global_min_scale, channel_min_scale, behind_min, must_compress).""" + """Return (global_min_scale, channel_min_scale, behind_min, must_compress). + + Scales against Beijing 20:00 / 90% front-load, not linear midnight pace. + """ + from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota + + plan = fleet_pace_plan(push_date, now=now) ch = db.get_shorts_channel(channel_pk) if channel_pk else None - used = db.shorts_channel_upload_count(channel_pk, push_date) if channel_pk else 0 - from .db import SHORTS_DAILY_FORCE - - daily_max = SHORTS_DAILY_FORCE - daily_min = SHORTS_DAILY_FORCE - day_start, day_end = beijing_day_bounds(push_date) - span = max(1.0, day_end - day_start) - day_progress = max(0.0, min(1.0, (now - day_start) / span)) - time_left = max(0.0, day_end - now) - remaining_slots = max(0, daily_max - used) - - expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05) - behind_min = used < daily_min and used < expected_min - behind_max = remaining_slots > 0 and used < daily_max * day_progress * 0.9 - must_compress = remaining_slots > 0 and time_left < 3600 * remaining_slots * 0.55 + used = db.shorts_channel_uploaded_count(channel_pk, push_date) if channel_pk else 0 + daily_min = _normalize_daily_quota((ch or {}).get("daily_min"), default=SHORTS_DAILY_FORCE) + daily_max = _normalize_daily_quota((ch or {}).get("daily_max"), default=SHORTS_DAILY_FORCE) + if daily_max < daily_min: + daily_max = daily_min + ch_front = max(1, int(math.ceil(QUOTA_FRONTLOAD_RATIO * daily_max))) + progress = float(plan.get("deadline_progress") or 0) + expected_ch = ch_front * progress if plan.get("before_deadline") else float(ch_front) + behind_min = used < daily_min and used < expected_ch + remaining_to_front = max(0, ch_front - used) + time_left = float(plan.get("time_left_sec") or 1) + must_compress = bool(plan.get("urgent")) or ( + remaining_to_front > 0 and time_left < remaining_to_front * CHANNEL_GAP_FLOOR_SEC * 1.05 + ) g_scale = 1.0 c_scale = 1.0 - if behind_min: - g_scale = min(g_scale, 0.45) - c_scale = min(c_scale, 0.3) - elif behind_max and day_progress > 0.35: - g_scale = min(g_scale, 0.65) - c_scale = min(c_scale, 0.5) - if must_compress or (day_progress > 0.82 and remaining_slots > 0): - per_slot = time_left / max(1, remaining_slots) - c_scale = min(c_scale, max(0.15, per_slot / 2400.0)) - g_scale = min(g_scale, max(0.2, c_scale * 0.75)) - return g_scale, c_scale, behind_min, must_compress or (day_progress > 0.9 and remaining_slots > 0) + if plan.get("behind") or behind_min: + # Map recommended gaps onto configured floors via scale. + rec_g = float(plan.get("recommended_global_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + rec_c = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + g_scale = min(1.0, rec_g / max(CHANNEL_GAP_FLOOR_SEC, 1.0)) + c_scale = min(1.0, rec_c / max(CHANNEL_GAP_FLOOR_SEC, 1.0)) + if must_compress: + g_scale = min(g_scale, 0.35) + c_scale = min(c_scale, 0.35) + return g_scale, c_scale, behind_min or bool(plan.get("behind")), must_compress + + +def _effective_gaps( + *, + channel_pk: str, + push_date: str, + now: float, + configured_global: float, + configured_channel: float, +) -> tuple[float, float, bool, bool]: + """Scaled global/channel gaps; prefer fleet_pace_plan recommendations when behind.""" + plan = fleet_pace_plan(push_date, now=now) + g_scale, c_scale, behind_min, urgent = _quota_pressure( + channel_pk=channel_pk, push_date=push_date, now=now + ) + if plan.get("behind") or urgent: + global_min = float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC) + channel_min = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + global_min = max(EMERGENCY_GLOBAL_GAP_SEC, min(configured_global, global_min)) + channel_min = max( + EMERGENCY_CHANNEL_GAP_SEC if urgent else CHANNEL_GAP_FLOOR_SEC, + min(configured_channel, channel_min), + ) + if not urgent: + channel_min = max(CHANNEL_GAP_FLOOR_SEC, channel_min) + global_min = max(GLOBAL_GAP_FLOOR_SEC, global_min) + else: + global_min = max(GLOBAL_GAP_FLOOR_SEC, configured_global * g_scale) + channel_min = max(CHANNEL_GAP_FLOOR_SEC, configured_channel * c_scale) + return global_min, channel_min, behind_min, urgent def pick_upload_at( @@ -81,30 +232,50 @@ def pick_upload_at( push_date: str = "", cfg: dict[str, Any] | None = None, ) -> float: - """Pick a jittered upload time within the Beijing day, avoiding clustering.""" + """Pick upload time biased into Beijing 00:00–20:00 when still under 90% target.""" settings = cfg or db.get_settings_map() now = time.time() day = push_date or push_date_from_ts(now) day_end = _day_end_ts(day) - latest = day_end - 45 + deadline = _deadline_ts(day) + plan = fleet_pace_plan(day, now=now, cfg=settings) + # Soft cap: schedule inside front-load window while we still need 90% before 20:00. + if plan.get("before_deadline") and int(plan.get("need_front") or 0) > 0: + latest = min(day_end - 45.0, deadline - 30.0) + else: + latest = day_end - 45.0 + latest = max(now + 20.0, latest) if not settings.get("shorts_upload_spread", True): return min(now + random.uniform(20, 120), latest) - global_min = max(300.0, float(settings.get("shorts_upload_min_gap_sec") or 720)) - channel_min = max(global_min, float(settings.get("shorts_channel_min_gap_sec") or 2400)) - g_scale, c_scale, behind_min, urgent = _quota_pressure( - channel_pk=channel_pk, push_date=day, now=now + configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC) + global_min, channel_min, behind_min, urgent = _effective_gaps( + channel_pk=channel_pk, + push_date=day, + now=now, + configured_global=max(GLOBAL_GAP_FLOOR_SEC, configured_global), + configured_channel=max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global), ) - global_min *= g_scale - channel_min *= c_scale if urgent or behind_min: - earliest = now + random.uniform(45, 240) + earliest = now + random.uniform(8, max(35.0, min(120.0, channel_min * 0.25))) else: - earliest = now + random.uniform(180, 1500) + # Ahead: mild jitter, still keep inside front-load window (not dump to 23:00). + earliest = now + random.uniform(60, min(900.0, channel_min * 0.8)) if earliest >= latest: - earliest = now + random.uniform(30, max(90.0, global_min * 0.4)) + earliest = now + random.uniform(8, 45) + + ch_last = db.shorts_channel_last_slot_ts(channel_pk, day) if channel_pk else 0.0 + if ch_last > 0: + slotted = ch_last + channel_min + random.uniform(3, 25) + if (urgent or behind_min) and slotted > latest: + earliest = max(earliest, now + 8) + else: + earliest = max(earliest, slotted) + if urgent and earliest > latest: + return float(min(now + random.uniform(8, 25), max(now + 5, latest))) slots = _occupied_slots(day) @@ -113,31 +284,110 @@ def pick_upload_at( gap = abs(ts - other_ts) if gap < global_min * random.uniform(0.85, 1.15): return True - if other_ch == channel_pk and gap < channel_min * random.uniform(0.9, 1.2): + if other_ch == channel_pk and gap < channel_min: return True return False - window_end = max(earliest + 60, latest) - for _ in range(48): - if random.random() < 0.35: - span = max(600.0, (window_end - earliest) / 8) - cand = earliest + random.expovariate(1.0 / span) - cand = min(cand, window_end) + # Prefer near-term slots when behind; never sample the whole day until midnight. + if urgent or behind_min: + window_end = min(latest, max(earliest + 600.0, now + max(global_min * 4, 1800.0))) + else: + window_end = min(latest, max(earliest + 1800.0, now + 3 * 3600.0)) + window_end = max(earliest + 60.0, window_end) + + for _ in range(64): + if urgent or behind_min: + # Bias early: half near earliest, half uniform in short window. + if random.random() < 0.55: + cand = earliest + random.uniform(0, max(90.0, global_min * 1.2)) + else: + cand = random.uniform(earliest, window_end) else: - cand = random.uniform(earliest, window_end) + if random.random() < 0.4: + span = max(300.0, (window_end - earliest) / 6) + cand = earliest + random.expovariate(1.0 / span) + cand = min(cand, window_end) + else: + cand = random.uniform(earliest, window_end) if cand < earliest: - cand = earliest + random.uniform(0, 120) + cand = earliest + random.uniform(0, 90) if not conflicts(cand): return float(min(cand, latest)) last_ts = max((s[0] for s in slots), default=now) - cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.8)) - ch_last = max((s[0] for s in slots if s[1] == channel_pk), default=0.0) - if ch_last: - cand = max(cand, ch_last + random.uniform(channel_min, channel_min * 1.8)) + cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.2)) + ch_last2 = max((s[0] for s in slots if s[1] == channel_pk), default=ch_last) + if ch_last2: + cand = max(cand, ch_last2 + channel_min + random.uniform(3, 40)) return float(min(cand, latest)) +def pull_forward_due_uploads(cfg: dict[str, Any] | None = None) -> int: + """Reschedule far-future slots when behind Beijing 20:00 / 90% pace.""" + settings = cfg or db.get_settings_map() + if not settings.get("shorts_auto_upload", True): + return 0 + now = time.time() + day = push_date_from_ts(now) + plan = fleet_pace_plan(day, now=now, cfg=settings) + if int(plan.get("total_gap") or 0) <= 0: + return 0 + # Always pull when behind front-load; also near midnight if still gapped. + if not plan.get("behind") and not plan.get("urgent"): + if plan.get("before_deadline") and float(plan.get("deadline_progress") or 0) < 0.85: + return 0 + if float(plan.get("time_left_sec") or 0) > 7200 and int(plan.get("total_gap") or 0) < 20: + return 0 + slam = bool(plan.get("urgent")) or ( + not plan.get("before_deadline") and float(plan.get("time_left_sec") or 0) < 2400 + ) + behind = bool(plan.get("behind")) + rec_g = max(EMERGENCY_GLOBAL_GAP_SEC, float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC)) + rec_c = max( + EMERGENCY_CHANNEL_GAP_SEC if slam else CHANNEL_GAP_FLOOR_SEC, + float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC), + ) + # When behind: anything parked beyond ~2× recommended global gap must come forward. + park_limit = now + (max(120.0, rec_g * 2.5) if (behind or slam) else 3600.0) + deadline = float(plan.get("deadline_ts") or _deadline_ts(day)) + latest = min(_day_end_ts(day) - 45.0, deadline - 30.0) if plan.get("before_deadline") else _day_end_ts(day) - 45.0 + + data = db.list_shorts_jobs(push_date=day, status="scheduled", limit=300, offset=0) + extra = db.list_shorts_jobs(push_date=day, status="recorded", limit=100, offset=0) + jobs = list(data.get("jobs") or []) + list(extra.get("jobs") or []) + # Stable order: soonest first so we pack from "now" + jobs.sort(key=lambda j: float(j.get("upload_at") or 0) or 1e18) + + # Cursor per channel + global for packing + next_global = now + random.uniform(5, 25) + next_ch: dict[str, float] = {} + moved = 0 + for job in jobs: + if not str(job.get("clip_path") or "").strip(): + continue + upload_at = float(job.get("upload_at") or 0) + if upload_at <= 0: + upload_at = now + 3600 + if not slam and not behind and upload_at <= park_limit: + continue + if (behind or slam) and upload_at <= park_limit: + continue + ch_pk = str(job.get("channel_pk") or "") + if slam or behind: + cand = max(next_global, next_ch.get(ch_pk, now)) + cand += random.uniform(2, 18) + cand = min(cand, max(now + 30.0, latest)) + new_at = float(cand) + next_global = new_at + rec_g + next_ch[ch_pk] = new_at + rec_c + else: + new_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=settings) + if slam or behind or new_at < upload_at - 30: + db.update_shorts_job(str(job["id"]), upload_at=new_at, error="") + moved += 1 + return moved + + def schedule_board(limit: int = 24) -> dict[str, Any]: """Upcoming scheduled uploads + per-channel today usage for UI.""" day = push_date_from_ts(time.time()) @@ -150,14 +400,20 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: for j in data.get("jobs") or []: ch = str(j.get("channel_pk") or "") st = str(j.get("status") or "") - bucket = by_ch.setdefault(ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) + bucket = by_ch.setdefault( + ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0} + ) if st in db._SHORTS_QUOTA_STATUSES: bucket["used"] += 1 if st == "uploaded" or st == "done": bucket["uploaded"] += 1 if st == "scheduled": bucket["scheduled"] += 1 - if st in {"pending", "recording"}: + if st == "recorded": + bucket["recorded"] += 1 + if st == "recording": + bucket["recording"] += 1 + if st == "pending": bucket["pending"] += 1 clip = str(j.get("clip_path") or "").strip() clip_ready = bool(clip) and Path(clip).is_file() @@ -228,10 +484,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: daily_max = _normalize_daily_quota(c.get("daily_max"), default=SHORTS_DAILY_FORCE) if daily_max < daily_min: daily_max = daily_min - stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) - used = int(stats["used"]) - gap = max(0, daily_max - used) - min_met = used >= daily_min + stats = by_ch.get( + cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0} + ) + pipeline = int(stats["used"]) + uploaded = int(stats["uploaded"]) + # UI progress / 缺 / 已满 = uploads only; pipeline stays in stats.used for ops. + gap = max(0, daily_max - uploaded) + min_met = uploaded >= daily_min if c.get("enabled") and not min_met: min_unmet += 1 if c.get("enabled"): @@ -250,8 +510,9 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "daily_max": daily_max, "gap": gap, "min_met": min_met, - "max_met": used >= daily_max, - "behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min), + "max_met": uploaded >= daily_max, + "behind_pace": bool(c.get("enabled") and uploaded < expected_min and uploaded < daily_min), + "pipeline": pipeline, "yt_profile": youtube_manage._snippet_from_channel_row(c), "last_status": str(c.get("last_status") or "offline"), "last_title": str(c.get("last_title") or ""), @@ -266,21 +527,76 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: else ypp_by_shorts.get(cid, -1) ), **stats, + # Progress fields must win over stats.used (pipeline occupancy). + "used": uploaded, + "uploaded": uploaded, + "pipeline": pipeline, } ) timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end) - # Lightweight YT quota forecast: if many uploads still pending vs remaining day hours - pending_uploads = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"}) + enabled_rows = [c for c in channel_rows if c.get("enabled")] + uploaded_total = sum(int(c.get("uploaded") or 0) for c in enabled_rows) + target_total = sum(int(c.get("daily_max") or 0) for c in enabled_rows) + pending_record = sum(int(c.get("pending") or 0) + int(c.get("recording") or 0) for c in enabled_rows) + queued_upload = sum( + int(c.get("scheduled") or 0) + int(c.get("recorded") or 0) for c in enabled_rows + ) + clip_ready = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"}) + plan = fleet_pace_plan(day, now=now) hours_left = max(0.1, (day_end - now) / 3600.0) + hours_to_deadline = max(0.0, (float(plan["deadline_ts"]) - now) / 3600.0) if plan.get("before_deadline") else 0.0 + impossible = total_gap > 0 and hours_left * 3600.0 < total_gap * CHANNEL_GAP_FLOOR_SEC * 0.85 + warn = ( + bool(plan.get("behind")) + or (total_gap >= 8 and hours_left < 4) + or impossible + or (pending_record >= 20 and hours_left < 2) + ) + # Human order: uploaded/target first, then gap, then in-flight pipeline (not additive to gap). + parts: list[str] = [f"已上传 {uploaded_total}/{target_total or '—'}"] + if total_gap > 0: + parts.append(f"缺口 {total_gap}") + else: + parts.append("已满") + pipe_bits: list[str] = [] + if queued_upload > 0: + pipe_bits.append(f"待传 {queued_upload}") + if pending_record > 0: + pipe_bits.append(f"待录 {pending_record}") + if pipe_bits: + parts.append("管道 " + " + ".join(pipe_bits)) + else: + parts.append("管道空") + parts.append(f"剩 {hours_left:.1f}h") + parts.append( + f"目标{QUOTA_DEADLINE_HOUR}:00前{int(QUOTA_FRONTLOAD_RATIO * 100)}%" + f"({plan.get('uploaded')}/{plan.get('front_target')})" + ) + if plan.get("behind"): + parts.append( + f"建议间隔≈{int(round(float(plan.get('recommended_global_gap_sec') or 0) / 60))}分" + f"/同频道≈{int(round(float(plan.get('recommended_channel_gap_sec') or 0) / 60))}分" + ) + if impossible: + parts.append("日末加速中") + elif plan.get("behind"): + parts.append("落后已加速") + elif warn: + parts.append("节奏偏紧") quota_forecast = { - "pending_uploads": pending_uploads, + "uploaded": uploaded_total, + "target": target_total, + "total_gap": total_gap, + "pending_record": pending_record, + "queued_upload": queued_upload, + "clip_ready": clip_ready, + "pending_uploads": queued_upload, "hours_left": round(hours_left, 2), - "per_hour_pace": round(pending_uploads / hours_left, 2) if hours_left else pending_uploads, - "warn": pending_uploads >= 8 and hours_left < 4, - "message": ( - f"今日仍有 {pending_uploads} 条待传,约剩 {hours_left:.1f} 小时" - + (",节奏偏紧,建议错开或延后低优任务" if pending_uploads >= 8 and hours_left < 4 else "") - ), + "hours_to_deadline": round(hours_to_deadline, 2), + "per_hour_pace": round(float(plan.get("recommended_per_hour") or 0), 2), + "warn": warn, + "pace": plan, + "message": " · ".join(parts), } return { "push_date": day, diff --git a/backend/app/shorts_yt_quota.py b/backend/app/shorts_yt_quota.py index cf946c5..68159ec 100644 --- a/backend/app/shorts_yt_quota.py +++ b/backend/app/shorts_yt_quota.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- """YouTube Data API upload counters — per OAuth Client profile (A/B/C/D). -Counters are display-only. This module must NEVER gate manual or worker uploads; -YouTube API 429 responses are the sole authority. Client A exhaustion must NOT -pause Client B either. +Local upload *counts* are display-only and must not gate uploads by themselves. +When YouTube returns a real 429 / quota-exceeded, we set a short API cool-down +per Client so the worker stops hammering (and ntfy spam). Manual upload paths +never consult that cool-down. """ from __future__ import annotations @@ -11,11 +12,12 @@ import time from typing import Any from . import db -from .shorts_upload import quota_error_message from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90 QUOTA_MAP_KEY = "shorts_yt_quota_by_profile" +# After a real YouTube 429, pause auto-uploads for this Client (manual still OK). +DEFAULT_API_COOLDOWN_SEC = 3600.0 def normalize_profile_id(raw: Any) -> str: @@ -40,8 +42,19 @@ def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int: return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT)) +def api_cooldown_sec(cfg: dict[str, Any] | None = None) -> float: + settings = cfg if cfg is not None else db.get_settings_map() + try: + return max( + 300.0, + min(12 * 3600.0, float(settings.get("shorts_yt_quota_cooldown_sec") or DEFAULT_API_COOLDOWN_SEC)), + ) + except (TypeError, ValueError): + return DEFAULT_API_COOLDOWN_SEC + + def _empty_entry() -> dict[str, Any]: - return {"date": "", "count": 0, "blocked_until": 0.0} + return {"date": "", "count": 0, "blocked_until": 0.0, "quota_ntfy_at": 0.0} def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]: @@ -56,6 +69,7 @@ def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]: "date": str(v.get("date") or ""), "count": int(v.get("count") or 0), "blocked_until": float(v.get("blocked_until") or 0), + "quota_ntfy_at": float(v.get("quota_ntfy_at") or 0), } # One-time migrate legacy global counters into profile A if map empty if not out: @@ -67,6 +81,7 @@ def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]: "date": legacy_date, "count": legacy_count, "blocked_until": legacy_until if legacy_until > time.time() else 0.0, + "quota_ntfy_at": 0.0, } return out @@ -92,7 +107,6 @@ def _count_uploads_from_db_pt_day(profile_id: str, day: str = "") -> int: with db._lock: conn = db._connect() try: - # Channels on this profile (empty profile_id counts as A) if pid == "A": ch_rows = conn.execute( """ @@ -162,15 +176,23 @@ def _sync_profile_entry( stored_day = str(entry.get("date") or "") stored_count = int(entry.get("count") or 0) blocked_until = float(entry.get("blocked_until") or 0) - if blocked_until and blocked_until <= time.time(): + ntfy_at = float(entry.get("quota_ntfy_at") or 0) + now = time.time() + if blocked_until and blocked_until <= now: blocked_until = 0.0 if stored_day != pt_day: db_count = _count_uploads_from_db_pt_day(pid, pt_day) stored_count = max(stored_count, db_count) if stored_day else db_count stored_day = pt_day - # New Pacific day clears block + # New Pacific day clears cool-down (YouTube quota also resets at PT midnight) blocked_until = 0.0 - entry = {"date": stored_day, "count": stored_count, "blocked_until": blocked_until} + ntfy_at = 0.0 + entry = { + "date": stored_day, + "count": stored_count, + "blocked_until": blocked_until, + "quota_ntfy_at": ntfy_at, + } quota_map[pid] = entry return entry @@ -185,7 +207,6 @@ def yt_upload_budget( limit = yt_daily_limit(settings) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(profile_id, settings, quota_map) - # Persist day roll if needed if settings.get(QUOTA_MAP_KEY) != quota_map: _save_quota_map(quota_map) settings[QUOTA_MAP_KEY] = quota_map @@ -199,14 +220,13 @@ def note_yt_upload_attempt( *, profile_id: str = "A", ) -> None: - """UI counter only — never gates uploads. YouTube API is the sole authority.""" + """UI counter only — does not clear API cool-down.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) pid = normalize_profile_id(profile_id) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(pid, settings, quota_map) entry["count"] = int(entry.get("count") or 0) + 1 entry["date"] = pacific_day_from_ts(time.time()) - entry["blocked_until"] = 0.0 quota_map[pid] = entry _save_quota_map(quota_map) @@ -216,7 +236,7 @@ def reserve_yt_upload_slot( *, profile_id: str = "A", ) -> bool: - """Always allow. Local 90-count is informational only — never refuse uploads.""" + """Always allow reservation for UI counter. Cool-down is enforced at claim time.""" note_yt_upload_attempt(cfg, profile_id=profile_id) return True @@ -226,14 +246,21 @@ def project_uploads_available( *, profile_id: str = "A", ) -> bool: - """Never self-block. Local budget is display-only.""" - _ = cfg, profile_id - return True + """True unless this Client is in a YouTube-API cool-down window.""" + blocked, _ = profile_upload_blocked(cfg, profile_id=profile_id) + return not blocked def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool: - _ = cfg - return True + """True if at least one Client is not in API cool-down (or map is empty).""" + settings = dict(cfg if cfg is not None else db.get_settings_map()) + blocked = blocked_profile_ids(settings) + if not blocked: + return True + for pid in ("A", "B", "C", "D"): + if pid not in blocked: + return True + return False def profile_upload_blocked( @@ -241,22 +268,29 @@ def profile_upload_blocked( *, profile_id: str = "A", ) -> tuple[bool, float]: - """Self-imposed pause removed: always unblocked. Clears stale blocked_until.""" + """True while YouTube API cool-down is active for this Client.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) pid = normalize_profile_id(profile_id) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(pid, settings, quota_map) - if float(entry.get("blocked_until") or 0) > 0: - entry["blocked_until"] = 0.0 - quota_map[pid] = entry - _save_quota_map(quota_map) + until = float(entry.get("blocked_until") or 0) + if until > time.time(): + return True, until return False, 0.0 def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]: - """No local upload pause — never skip profiles in the worker.""" - _ = cfg - return set() + """Clients currently in API cool-down (worker should skip auto-upload).""" + settings = dict(cfg if cfg is not None else db.get_settings_map()) + quota_map = _load_quota_map(settings) + out: set[str] = set() + now = time.time() + pids = set(quota_map.keys()) | {"A", "B", "C", "D"} + for pid in pids: + entry = _sync_profile_entry(pid, settings, quota_map) + if float(entry.get("blocked_until") or 0) > now: + out.add(pid) + return out def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]: @@ -271,18 +305,19 @@ def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str rows = [] for pid in profiles: limit, used, remaining = yt_upload_budget(settings, profile_id=pid) - # Clear any legacy self-pause; never report blocked for local enforcement - profile_upload_blocked(settings, profile_id=pid) + blocked, until = profile_upload_blocked(settings, profile_id=pid) rows.append( { "id": pid, "limit": limit, "used": used, "remaining": remaining, - "exhausted_hint": used >= limit, - "blocked": False, - "blocked_until": 0.0, - "reset_at": next_youtube_quota_reset_ts() if used >= limit else 0.0, + "exhausted_hint": bool(used >= limit and not blocked), + "blocked": blocked, + "blocked_until": until, + "reset_at": until + if blocked + else (next_youtube_quota_reset_ts() if used >= limit else 0.0), } ) return rows @@ -297,32 +332,95 @@ def channel_ids_for_profile(profile_id: str) -> list[str]: return ids +def mark_api_quota_cooldown( + cfg: dict[str, Any] | None = None, + *, + profile_id: str = "A", + reason: str = "", + cooldown_sec: float | None = None, +) -> tuple[float, bool]: + """Set cool-down after a real YouTube 429. Returns (until_ts, should_notify). + + should_notify is True only when entering / refreshing a cool-down for ntfy (once per window). + """ + settings = dict(cfg if cfg is not None else db.get_settings_map()) + pid = normalize_profile_id(profile_id) + cool = float(cooldown_sec) if cooldown_sec is not None else api_cooldown_sec(settings) + now = time.time() + reset_at = next_youtube_quota_reset_ts() + until = min(now + cool, reset_at) if reset_at > now else now + cool + quota_map = _load_quota_map(settings) + entry = _sync_profile_entry(pid, settings, quota_map) + prev_until = float(entry.get("blocked_until") or 0) + already = prev_until > now + 60 + entry["blocked_until"] = max(prev_until, until) if already else until + limit = yt_daily_limit(settings) + entry["count"] = max(int(entry.get("count") or 0), limit) + entry["date"] = pacific_day_from_ts(now) + last_ntfy = float(entry.get("quota_ntfy_at") or 0) + should_notify = (not already) or (now - last_ntfy >= cool * 0.9) + if should_notify: + entry["quota_ntfy_at"] = now + quota_map[pid] = entry + _save_quota_map(quota_map) + _ = reason + return float(entry["blocked_until"]), should_notify + + def pause_uploads_until_reset( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", reason: str = "", ) -> float: - """Legacy no-op: do NOT self-pause or defer jobs. Snap UI counter only.""" - settings = dict(cfg if cfg is not None else db.get_settings_map()) - pid = normalize_profile_id(profile_id) - until = next_youtube_quota_reset_ts() - quota_map = _load_quota_map(settings) - entry = _sync_profile_entry(pid, settings, quota_map) - entry["blocked_until"] = 0.0 - limit = yt_daily_limit(settings) - entry["count"] = max(int(entry.get("count") or 0), limit) - entry["date"] = pacific_day_from_ts(time.time()) - quota_map[pid] = entry - _save_quota_map(quota_map) - _ = reason + """Compatibility: apply default API cool-down.""" + until, _ = mark_api_quota_cooldown(cfg, profile_id=profile_id, reason=reason) return until def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int: - """No-op: never bulk-defer uploads for a Client. Manual upload must stay free.""" - _ = profile_id, until_ts, reason - return 0 + """Push due auto-uploads for this Client past cool-down (manual claim still free).""" + pid = normalize_profile_id(profile_id) + until = float(until_ts or 0) + if until <= time.time(): + return 0 + ch_ids = channel_ids_for_profile(pid) + if not ch_ids: + return 0 + moved = 0 + now = time.time() + with db._lock: + conn = db._connect() + try: + placeholders = ",".join("?" for _ in ch_ids) + rows = conn.execute( + f""" + SELECT id, upload_at FROM shorts_jobs + WHERE status IN ('scheduled', 'recorded') + AND clip_path != '' + AND youtube_video_id = '' + AND channel_pk IN ({placeholders}) + AND upload_at > 0 + AND upload_at <= ? + """, + (*ch_ids, now + 30), + ).fetchall() + for row in rows: + conn.execute( + "UPDATE shorts_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?", + ( + until + 15, + (reason or "YouTube 接口配额冷静中,稍后自动重试")[:300], + now, + str(row["id"]), + ), + ) + moved += 1 + if moved: + conn.commit() + finally: + conn.close() + return moved def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int: @@ -332,18 +430,20 @@ def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]: - """No-op: never auto-pause Clients from local counters or past 429s.""" + """No-op: cool-down is set only from live API 429 feedback.""" _ = cfg return {} def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None: - """Wipe legacy blocked_until / global pause so uploads are never locally gated.""" + """Clear expired cool-downs only — does not wipe an active API cool-down.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) quota_map = _load_quota_map(settings) changed = False + now = time.time() for pid, entry in list(quota_map.items()): - if float(entry.get("blocked_until") or 0) != 0: + until = float(entry.get("blocked_until") or 0) + if until and until <= now: entry = dict(entry) entry["blocked_until"] = 0.0 quota_map[pid] = entry @@ -352,6 +452,5 @@ def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None: _save_quota_map(quota_map) -# Back-compat aliases used by older call sites (treat as profile A) def pause_uploads_until_reset_global(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float: return pause_uploads_until_reset(cfg, profile_id="A", reason=reason) diff --git a/backend/app/youtube_client.py b/backend/app/youtube_client.py index 7637613..43c12a2 100644 --- a/backend/app/youtube_client.py +++ b/backend/app/youtube_client.py @@ -46,7 +46,8 @@ async def _request( async def health() -> dict[str, Any]: try: - return await _request("GET", "/health", timeout=12.0) + # Callers wrap with ~0.6s; keep internal timeout short to avoid half-open churn. + return await _request("GET", "/health", timeout=1.0) except YouTubeSvcError as exc: return {"ok": False, "error": str(exc), "service": "youtube-svc"} diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py index f9623e4..9d34009 100644 --- a/backend/app/youtube_live.py +++ b/backend/app/youtube_live.py @@ -20,6 +20,81 @@ _BATCH_SIZE = 20 _REFRESH_LOCK: Optional[asyncio.Lock] = None _LAST_OAUTH_AT = 0.0 _OAUTH_MIN_INTERVAL_SEC = 45.0 +# Studio samples older than this must not invent 在播 (edge_assign_live used to sticky-inflate). +_STUDIO_SAMPLE_MAX_AGE_SEC = 60.0 +_STUDIO_DEAD_STATUSES = { + "waiting", + "ended", + "signed_out", + "offline", + "encoder_lost", + "preparing", + "ready", +} +# Circular / untrusted for receiving: hub←edge assign_lives mirror. +_UNTRUSTED_SAMPLE_SOURCES = {"edge_assign_live", "edge_assign", "hub_mirror"} + + +def _studio_receiving_from_snap(studio_snap: dict[str, Any] | None) -> bool: + """True only for real Studio receiving — never Preparing / Excellent-alone / edge mirror junk.""" + snap = studio_snap if isinstance(studio_snap, dict) else {} + if not snap: + return False + if snap.get("encoder_lost") or snap.get("preparing_stream"): + return False + st = str(snap.get("live_status") or "").strip().lower() + if st in _STUDIO_DEAD_STATUSES: + return False + detect = str(snap.get("detect_source") or "").strip().lower() + if detect in _UNTRUSTED_SAMPLE_SOURCES: + return False + # age_sec from live snap; samples stash received_at + try: + age = snap.get("age_sec") + if age is None and snap.get("received_at"): + age = time.time() - float(snap.get("received_at") or 0) + if age is not None and float(age) > _STUDIO_SAMPLE_MAX_AGE_SEC: + return False + except (TypeError, ValueError): + pass + return bool(snap.get("encoder_receiving") or snap.get("on_air")) + + +def _studio_snap_belongs_to_assign_group( + studio_snap: dict[str, Any] | None, + *, + youtube_channel_id: str = "", + neko_shared: bool = False, + group_is_pushing: bool = False, + studio_url_hint: str = "", +) -> bool: + """Attribute Studio receiving only to the assign card that owns that session. + + Several cards can share one Neko browser. Telemetry for /video/…/livestreaming then + looks identical for every card on that instance — without this gate, a sibling's + on-air stream marks unrelated cards 「频道在播」. + """ + snap = studio_snap if isinstance(studio_snap, dict) else {} + if not snap: + return False + cid = str(youtube_channel_id or "").strip() + url = str(snap.get("url") or "").strip() + url_l = url.lower() + if cid and f"/channel/{cid.lower()}" in url_l: + return True + hint = str(studio_url_hint or "").strip() + if hint and "/video/" in hint and url: + try: + vid = hint.split("/video/", 1)[1].split("/", 1)[0].strip() + except Exception: + vid = "" + if vid and vid in url: + return True + if group_is_pushing: + return True + if not neko_shared: + return True + return False def _http_channel_live_probe(channel_id: str) -> dict[str, Any]: @@ -496,8 +571,15 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: seen_http.add(cid) http_cids.append(cid) if http_cids: + # Cap fan-out — each probe may try multiple proxies with long urllib timeouts. + sem = asyncio.Semaphore(int(os.environ.get("DY_LIVE_HTTP_PROBE_CONCURRENCY", "4") or "4")) + + async def _bounded(cid: str) -> Any: + async with sem: + return await asyncio.to_thread(_http_channel_live_probe, cid) + http_results = await asyncio.gather( - *[asyncio.to_thread(_http_channel_live_probe, cid) for cid in http_cids], + *[_bounded(cid) for cid in http_cids], return_exceptions=True, ) cid_to_targets: dict[str, list[dict[str, Any]]] = {} @@ -705,6 +787,16 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: assign_ent["title"] = gid_to_name[gid] entries[f"assign:{gid}"] = assign_ent + # Count assign cards per Neko — shared browsers must not cross-attribute Studio. + neko_share_count: dict[int, int] = {} + for g in assign_groups: + try: + nid = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid > 0: + neko_share_count[nid] = neko_share_count.get(nid, 0) + 1 + for g in assign_groups: gid = str(g.get("id") or "").strip() if not gid: @@ -712,6 +804,11 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: pk = str(g.get("channel_pk") or "").strip() row = relay_rows.get(gid) or {} cid = str(g.get("youtube_channel_id") or "").strip() + try: + group_neko_id = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + group_neko_id = 0 + neko_shared = bool(group_neko_id > 0 and neko_share_count.get(group_neko_id, 0) > 1) # Already marked live via youtubei/OAuth for this shorts/channel → receiving-level truth. prev_live = entries.get(f"assign:{gid}") or {} @@ -724,7 +821,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: studio_snap: dict[str, Any] = {} try: studio_snap = await asyncio.to_thread( - lambda gg=g: youtube_neko.studio_snapshot_for_group(gg, max_age_sec=120.0) + lambda gg=g: youtube_neko.studio_snapshot_for_group( + gg, max_age_sec=120.0, include_minute_reports=False + ) ) except Exception: studio_snap = {} @@ -766,29 +865,43 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {} st = str(payload.get("live_status") or "").lower() health = str(payload.get("health") or "").lower() + # Never invent receiving from Excellent/health alone (Preparing+Excellent bug). receiving = bool( signals.get("encoder_receiving") + or signals.get("on_air") or st == "live" - or health in {"excellent", "good"} + ) and not ( + signals.get("preparing_stream") + or st in _STUDIO_DEAD_STATUSES + or signals.get("encoder_lost") ) if not receiving: continue - if signals.get("encoder_lost") or st in {"encoder_lost", "waiting", "ended"}: + if signals.get("encoder_lost") or st in _STUDIO_DEAD_STATUSES: + continue + age = None + try: + age = time.time() - float(ev.get("received_at") or 0) + except (TypeError, ValueError): + age = None + if age is not None and age > _STUDIO_SAMPLE_MAX_AGE_SEC: continue studio_snap = { "on_air": True, - "encoder_receiving": True, + "encoder_receiving": bool(signals.get("encoder_receiving") or st == "live"), "live_page_open": True, "live_status": st or "live", "health": health, "viewer_count": payload.get("viewer_count"), "url": url[:200], "received_at": float(ev.get("received_at") or 0), + "age_sec": round(age, 1) if age is not None else None, "detect_source": "telemetry_url_match", } break - # DB samples (physical local Neko CDP) — fill when in-memory snap is quiet. + # DB samples (physical local Neko CDP / extension) — fill when in-memory snap is quiet. + # Never trust edge_assign_live mirrors (circular sticky 在播). if not ( studio_snap.get("on_air") or studio_snap.get("encoder_receiving") @@ -799,46 +912,60 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: samples = await asyncio.to_thread( lambda: yt_studio_db.list_samples( - group_id=gid, since_ts=now - 180.0, limit=5 + group_id=gid, since_ts=now - _STUDIO_SAMPLE_MAX_AGE_SEC, limit=5 ) ) if not samples and cid: samples = await asyncio.to_thread( lambda: yt_studio_db.list_samples( - youtube_channel_id=cid, since_ts=now - 180.0, limit=5 + youtube_channel_id=cid, + since_ts=now - _STUDIO_SAMPLE_MAX_AGE_SEC, + limit=5, ) ) except Exception: samples = [] for s in samples or []: + detect = str(s.get("detect_source") or "").strip().lower() + if detect in _UNTRUSTED_SAMPLE_SOURCES: + continue st = str(s.get("live_status") or "").lower() - if st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: + if st in _STUDIO_DEAD_STATUSES: + continue + if s.get("preparing_stream"): continue if not (s.get("on_air") or st == "live"): continue + try: + sample_age = now - float(s.get("ts") or 0) + except (TypeError, ValueError): + sample_age = 9999.0 + if sample_age > _STUDIO_SAMPLE_MAX_AGE_SEC: + continue studio_snap = { - "on_air": True, - "encoder_receiving": True, + "on_air": bool(s.get("on_air")), + "encoder_receiving": bool(s.get("on_air") or st == "live"), "live_page_open": bool(s.get("live_page_open") or True), "live_status": st or "live", "health": str(s.get("health") or ""), "viewer_count": s.get("viewer_count"), "url": str(s.get("studio_url") or "")[:200], "received_at": float(s.get("ts") or 0), - "detect_source": "yt_studio_samples", + "age_sec": round(sample_age, 1), + "detect_source": detect or "yt_studio_samples", "neko_ref": str(s.get("neko_ref") or ""), } break - receiving = bool( - ( - studio_snap.get("encoder_receiving") - or studio_snap.get("on_air") - ) - and not studio_snap.get("encoder_lost") - and str(studio_snap.get("live_status") or "").lower() - not in {"waiting", "ended", "signed_out", "offline", "encoder_lost"} - ) + receiving = _studio_receiving_from_snap(studio_snap) + if receiving and not _studio_snap_belongs_to_assign_group( + studio_snap, + youtube_channel_id=cid, + neko_shared=neko_shared, + group_is_pushing=bool(row.get("is_pushing")), + studio_url_hint=str(g.get("neko_studio_url") or ""), + ): + receiving = False # Collect public probe answers across assign / channel / shorts refs. public_sources = { diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py index bb1dd9e..297a279 100644 --- a/backend/app/youtube_manage.py +++ b/backend/app/youtube_manage.py @@ -673,3 +673,55 @@ async def channel_dashboard(channel_pk: str) -> dict[str, Any]: "recent_videos": listing.get("videos") or [], "shorts_today": {"push_date": day, "by_status": by_status, "total": local.get("total") or 0}, } + + +async def complete_active_live_broadcast(channel_pk: str) -> dict[str, Any]: + """Transition the channel's active liveBroadcast to ``complete`` (graceful End Stream via API). + + Quota: liveBroadcasts.list (~1) + liveBroadcasts.transition (~50). Prefer CDP click first. + """ + pk = str(channel_pk or "").strip() + if not pk: + return {"ok": False, "error": "empty_channel_pk"} + try: + token, _ch = await _access_for_channel(pk) + except Exception as exc: + return {"ok": False, "error": f"oauth:{str(exc)[:160]}"} + try: + data = await _get( + "liveBroadcasts", + token=token, + params={"part": "id,status", "mine": "true", "maxResults": 25}, + ) + except Exception as exc: + return {"ok": False, "error": f"list:{str(exc)[:160]}"} + items = data.get("items") or [] + live_ids: list[str] = [] + for it in items: + st = str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower() + bid = str(it.get("id") or "").strip() + if bid and st in {"live", "testing", "ready"}: + # Only complete truly live (or testing encoder) sessions. + if st == "live" or st == "testing": + live_ids.append(bid) + if not live_ids: + return {"ok": True, "skipped": "no_active_live", "count": 0} + completed: list[str] = [] + errors: list[str] = [] + for bid in live_ids[:3]: + try: + await _post( + "liveBroadcasts/transition", + token=token, + params={"broadcastStatus": "complete", "id": bid, "part": "status,id"}, + json_body={}, + ) + completed.append(bid) + except Exception as exc: + errors.append(f"{bid}:{str(exc)[:120]}") + return { + "ok": bool(completed) and not errors, + "completed": completed, + "errors": errors, + "attempted": live_ids[:3], + } diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py index 48ea126..1fe8412 100644 --- a/backend/app/youtube_neko.py +++ b/backend/app/youtube_neko.py @@ -292,24 +292,43 @@ def _wg_iface_usable(iface: str, *, peer: str, max_age_sec: int = 180) -> bool: return False +_cn_edge_cache: tuple[float, bool] | None = None +_CN_EDGE_CACHE_TTL_SEC = 30.0 + + def cn_edge_usable() -> bool: """Tencent wg-dy-cn preferred path for physical Neko HTTP/ICE. Prefer CN whenever the iface is up and either handshake is fresh or peer pings. Slightly stale handshake alone should not flip ICE to the overseas VPS IP. + Cached briefly — status/sync paths used to spawn ping -W 2 on every call and + saturate the default thread pool (Recv-Q hang / health timeout). """ - if not Path("/sys/class/net/wg-dy-cn").exists(): - return False - peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1" - if _wg_iface_usable("wg-dy-cn", peer=peer, max_age_sec=600): - return True - # iface present: still prefer CN if configured (operator intent) unless ping hard-fails - if peer: - c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6) - if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2): - return True - # Last resort: iface up counts as usable so NAT1TO1 stays on Tencent DNAT - return True + global _cn_edge_cache + import time as _time + + now = _time.time() + if _cn_edge_cache is not None: + cached_at, cached_ok = _cn_edge_cache + if now - cached_at < _CN_EDGE_CACHE_TTL_SEC: + return cached_ok + + ok = False + if Path("/sys/class/net/wg-dy-cn").exists(): + peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1" + if _wg_iface_usable("wg-dy-cn", peer=peer, max_age_sec=600): + ok = True + elif peer: + c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6) + if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2): + ok = True + else: + # Last resort: iface up counts as usable so NAT1TO1 stays on Tencent DNAT + ok = True + else: + ok = True + _cn_edge_cache = (now, ok) + return ok def _derive_cn_public_base(primary: str) -> str: @@ -493,6 +512,9 @@ def compose_service_lines( max_fps = str(getattr(settings, "neko_max_fps", "") or "10") bitrate = str(getattr(settings, "neko_video_bitrate", "") or "700") icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0") + mem_limit = str(getattr(settings, "neko_mem_limit", "") or "1536m").strip() + if mem_limit.lower() in {"", "0", "none", "off", "unlimited"}: + mem_limit = "" start_url = str( getattr(settings, "neko_start_url", "") or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/" @@ -512,11 +534,26 @@ def compose_service_lines( raise RuntimeError(f"Neko sh2 asset missing: {required}") _ensure_browser_launch_exec() bind = (http_bind or _http_bind()).strip() or "127.0.0.1" - return [ + lines = [ f" {service_key}:", f" image: {_q(image)}", ' restart: "no"', f" shm_size: {_q(shm)}", + ] + # Hard cap: runaway Studio/Chrome OOMs the container, not the whole VPS. + # Negative oom_score_adj: host kills API/other apps before Neko/Chrome. + if mem_limit: + lines.extend( + [ + f" mem_limit: {_q(mem_limit)}", + f" memswap_limit: {_q(mem_limit)}", + " oom_score_adj: -800", + ] + ) + else: + lines.append(" oom_score_adj: -800") + lines.extend( + [ " cap_add:", " - SYS_ADMIN", " security_opt:", @@ -573,7 +610,9 @@ def compose_service_lines( 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/{supervisor_name}:ro')}", - ] + ] + ) + return lines def _render_compose(count: int) -> str: @@ -678,8 +717,14 @@ def _container_state(instance_id: int, *, check_http: bool = False) -> dict[str, running = bool(state.get("Running")) health = str((state.get("Health") or {}).get("Status") or "") out["running"] = running + out["oom_killed"] = bool(state.get("OOMKilled")) + try: + out["exit_code"] = int(state.get("ExitCode") or 0) + except (TypeError, ValueError): + out["exit_code"] = 0 + out["finished_at"] = str(state.get("FinishedAt") or "")[:40] if not running: - out["status"] = "stopped" + out["status"] = "oom" if out["oom_killed"] else "stopped" else: out["status"] = health if health else "running" if running: @@ -1200,6 +1245,162 @@ def sync_for_groups( return ensure_capacity(desired, start_instances=start_set, reconcile_running=reconcile_running) +def _graceful_chrome_quit(instance_id: int, *, wait_sec: float = 6.0) -> dict[str, Any]: + """Ask Chrome inside Neko to exit cleanly so Sessions/tabs flush before docker stop.""" + import time as _time + + name = _container_name(instance_id) + # SIGTERM chrome first (session flush); fall back to pkill names used in image. + script = ( + "set +e; " + "pkill -TERM -f '/opt/google/chrome/chrome' 2>/dev/null; " + "pkill -TERM -f 'google-chrome' 2>/dev/null; " + "pkill -TERM -f 'chromium' 2>/dev/null; " + "exit 0" + ) + _run(["docker", "exec", name, "sh", "-c", script], timeout=10) + deadline = _time.time() + max(2.0, float(wait_sec)) + while _time.time() < deadline: + code, out = _run( + [ + "docker", + "exec", + name, + "sh", + "-c", + "pgrep -f '/opt/google/chrome/chrome|google-chrome|chromium' >/dev/null 2>&1; echo $?", + ], + timeout=8, + ) + # echo $? → 1 means no matching process + if (out or "").strip().splitlines()[-1:] == ["1"]: + return {"ok": True, "quit": True} + _time.sleep(0.4) + return {"ok": True, "quit": False, "note": "chrome_still_running"} + + +def cdp_end_studio_stream(instance_id: int) -> dict[str, Any]: + """Click Studio End Stream (+ confirm) via CDP inside a running Neko.""" + idx = int(instance_id or 0) + if idx < 1: + return {"ok": False, "error": "bad_id"} + st = _container_state(idx, check_http=False) + if not st.get("running"): + return {"ok": False, "error": "neko_not_running", "id": idx} + script = _asset_root() / "cdp_end_stream.py" + if not script.is_file(): + return {"ok": False, "error": "end_stream_script_missing"} + try: + script_text = script.read_text(encoding="utf-8") + except OSError as exc: + return {"ok": False, "error": f"read_script:{exc}"} + name = _container_name(idx) + # Prefer focusing live tab first (no-op if already open). + try: + _cdp_nudge_live_studio_tab(idx) + except Exception: + pass + code, out = _run( + ["docker", "exec", "-i", name, "python3", "-"], + timeout=35, + input_text=script_text, + ) + try: + line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}" + row = json.loads(line) + if isinstance(row, dict): + row["id"] = idx + return row + except Exception: + pass + return {"ok": False, "id": idx, "error": (out or f"exit_{code}")[:220]} + + +def end_live_session( + instance_id: int, + *, + channel_pk: str = "", + wait_encoder_lost_sec: float = 12.0, + settle_sec: float = 3.0, +) -> dict[str, Any]: + """Graceful YouTube live end while Neko is still up. + + Order: wait briefly for encoder-lost UI → CDP End Stream → OAuth complete fallback. + Does **not** stop the Neko container. + """ + import time as _time + + idx = int(instance_id or 0) + out: dict[str, Any] = {"ok": False, "id": idx, "steps": []} + if idx < 1: + out["error"] = "bad_id" + return out + st = _container_state(idx, check_http=False) + if not st.get("running"): + out["ok"] = True + out["skipped"] = "neko_not_running" + return out + + # Give Studio a moment to flip Excellent → No data after FFmpeg stop. + wait_need = max(0.0, float(wait_encoder_lost_sec)) + deadline = _time.time() + wait_need + saw_lost = False + while _time.time() < deadline: + try: + sig = _cdp_studio_page_signals(idx, max_age_sec=0.0, force=True) + except Exception: + sig = {} + live_status = str((sig or {}).get("live_status") or "").lower() + if live_status in {"encoder_lost", "ended", "waiting"} or not bool((sig or {}).get("on_air")): + if live_status == "ended": + out["ok"] = True + out["steps"].append({"cdp_wait": "already_ended"}) + return out + saw_lost = True + break + _time.sleep(1.0) + out["steps"].append({"encoder_lost_wait": True, "saw_hint": saw_lost}) + + cdp = cdp_end_studio_stream(idx) + out["steps"].append({"cdp_end": cdp}) + cdp_ok = bool(cdp.get("ok")) + + api: dict[str, Any] = {"skipped": True} + if (not cdp_ok) and str(channel_pk or "").strip(): + try: + import asyncio + + from . import youtube_manage + + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + # Sync caller inside async context — use a dedicated loop in a thread. + import concurrent.futures + + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + api = pool.submit( + lambda: asyncio.run( + youtube_manage.complete_active_live_broadcast(str(channel_pk)) + ) + ).result(timeout=60) + else: + api = asyncio.run(youtube_manage.complete_active_live_broadcast(str(channel_pk))) + except Exception as exc: + api = {"ok": False, "error": str(exc)[:200]} + out["steps"].append({"api_complete": api}) + + settle = max(0.0, float(settle_sec)) + if settle: + _time.sleep(settle) + out["ok"] = cdp_ok or bool(api.get("ok") or api.get("skipped") == "no_active_live") + if not out["ok"] and not out.get("error"): + out["error"] = "end_stream_unconfirmed" + return out + + def stop_instance(instance_id: int) -> dict[str, Any]: """Stop one Neko container (time-slot off-duty). Does not change neko_enabled.""" idx = int(instance_id or 0) @@ -1208,7 +1409,12 @@ def stop_instance(instance_id: int) -> dict[str, Any]: st = _container_state(idx) if not st.get("running"): return {"ok": True, "id": idx, "already_stopped": True} - code, out = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45) + # Flush Chrome session before container SIGKILL window — keeps operator tabs on next start. + try: + _graceful_chrome_quit(idx, wait_sec=6.0) + except Exception: + pass + code, out = _run(["docker", "stop", "-t", "12", _container_name(idx)], timeout=50) if code != 0: return {"ok": False, "id": idx, "error": (out or "stop failed")[:300]} return {"ok": True, "id": idx, "stopped": True} @@ -1225,8 +1431,8 @@ def stop_instances_except(keep_instance_id: int) -> list[int]: st = _container_state(idx) if not st.get("running"): continue - code, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45) - if code == 0: + res = stop_instance(idx) + if res.get("ok") and res.get("stopped"): stopped.append(idx) return stopped @@ -1248,6 +1454,412 @@ def ensure_instance_running(instance_id: int) -> dict[str, Any]: return {"ok": True, "id": idx, "started": True} +# Soft heal: restart crashed/OOM Nekos that Live still needs. Never wipe volumes. +_NEKO_HEAL_LAST: dict[int, float] = {} +_NEKO_HEAL_COOLDOWN_SEC = 180.0 + + +def _neko_ids_needed_for_live() -> set[int]: + """Instances that must stay up: DB enabled, exclusive winner, or actively pushing.""" + needed: set[int] = set() + try: + from . import yt_assign_db + + for g in yt_assign_db.list_groups(include_urls=False): + try: + nid = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid < 1: + continue + if g.get("neko_enabled"): + needed.add(nid) + except Exception: + pass + try: + from . import youtube_relay_db + from .youtube_relay_pipeline import youtube_relay_pipeline + + winner = str(getattr(youtube_relay_pipeline, "_exclusive_winner", None) or "").strip() + if winner: + from . import yt_assign_db + + wg = yt_assign_db.get_group(winner) or {} + try: + wn = int(wg.get("neko_instance_id") or 0) + except (TypeError, ValueError): + wn = 0 + if wn > 0: + needed.add(wn) + for row in youtube_relay_db.list_relay_states(): + st = str(row.get("status") or "") + if st not in {"pushing", "starting", "reconnecting"}: + continue + gid = str(row.get("group_id") or "") + if not gid: + continue + from . import yt_assign_db + + g = yt_assign_db.get_group(gid) or {} + try: + nid = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid > 0: + needed.add(nid) + except Exception: + pass + # In-memory sessions are authoritative after API restart orphans DB rows. + try: + from .youtube_relay_pipeline import youtube_relay_pipeline + from . import yt_assign_db + + for gid in list(getattr(youtube_relay_pipeline, "_sessions", {}) or {}): + g = yt_assign_db.get_group(str(gid)) or {} + try: + nid = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid > 0: + needed.add(nid) + except Exception: + pass + return needed + + +def heal_crashed_assign_nekos() -> dict[str, Any]: + """If a needed Neko exited / OOM-killed, docker start it (profile volumes untouched). + + Does NOT start idle disabled instances. Cooldown 180s per instance. + """ + import time as _time + + needed = _neko_ids_needed_for_live() + if not needed: + return {"ok": True, "needed": 0, "healed": [], "skipped": []} + now = _time.time() + healed: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + for nid in sorted(needed): + last = float(_NEKO_HEAL_LAST.get(nid) or 0) + if now - last < _NEKO_HEAL_COOLDOWN_SEC: + skipped.append({"id": nid, "reason": "cooldown"}) + continue + st = _container_state(nid, check_http=False) + if st.get("running"): + skipped.append({"id": nid, "reason": "already_running"}) + continue + reason = "oom" if st.get("oom_killed") else f"exit:{st.get('exit_code')}" + _NEKO_HEAL_LAST[nid] = now + res = ensure_instance_running(nid) + healed.append({"id": nid, "reason": reason, "result": res}) + return {"ok": True, "needed": len(needed), "healed": healed, "skipped": skipped} + + +_CHROME_HEAL_LAST: dict[int, float] = {} +_CHROME_HEAL_COOLDOWN_SEC = 120.0 +_CDP_FAIL_STREAK: dict[int, int] = {} +_RENDERER_FAIL_STREAK: dict[int, int] = {} + + +def _devtools_version_ok(instance_id: int) -> bool: + name = _container_name(instance_id) + code, _out = _run( + [ + "docker", + "exec", + name, + "bash", + "-lc", + "curl -fsS -m 2 http://127.0.0.1:9222/json/version >/dev/null 2>&1 " + "|| wget -q -T 2 -O /dev/null http://127.0.0.1:9222/json/version >/dev/null 2>&1", + ], + timeout=12, + ) + return code == 0 + + +def _chrome_log_recent_sigill(instance_id: int, *, window_sec: int = 600) -> bool: + """True if google-chrome.log mentions SIGILL and was written recently.""" + name = _container_name(instance_id) + # mtime within window + any SIGILL/Illegal instruction hit in the log file. + py = ( + "import os,re,time\n" + f"win={int(window_sec)}\n" + "p='/var/log/neko/google-chrome.log'\n" + "try:\n" + " st=os.stat(p)\n" + "except OSError:\n" + " print('0'); raise SystemExit\n" + "if time.time()-st.st_mtime>win:\n" + " print('0'); raise SystemExit\n" + "try:\n" + " data=open(p,'rb').read()[-250000].decode('utf-8','ignore')\n" + "except OSError:\n" + " print('0'); raise SystemExit\n" + "print('1' if re.search(r'SIGILL|Illegal instruction|STATUS_INVALID_IMAGE_HASH|" + "Aw,\\s*Snap', data, re.I) else '0')\n" + ) + code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=12) + return code == 0 and str(out or "").strip().endswith("1") + + +def _chrome_renderer_probe(instance_id: int) -> str: + """Probe real page DOM via CDP Runtime.evaluate. + + Tab metadata often still says "YouTube Creator Studio" while Aw Snap / SIGILL + is on screen — evaluate title/body (or timeout) is the reliable signal. + Empty string = healthy / inconclusive (no page tab). + """ + name = _container_name(instance_id) + # Compact WS client — same framing as cdp_studio_scrape.py; 4s eval deadline. + script = r''' +import base64,json,os,socket,struct,sys,time,urllib.request +def ws_connect(url): + hostport,path=url[5:].split('/',1); path='/'+path + host,port=hostport.split(':'); port=int(port) + key=base64.b64encode(os.urandom(16)).decode() + s=socket.create_connection((host,port),timeout=5) + s.settimeout(5) + s.sendall(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()) + buf=b'' + while b'\r\n\r\n' not in buf: + c=s.recv(4096) + if not c: raise RuntimeError('hs') + buf+=c + return s +def ws_send(s,payload): + data=json.dumps(payload).encode(); mask=os.urandom(4) + h=bytearray([0x81]); n=len(data) + if n<126: h.append(0x80|n) + elif n<65536: h.append(0x80|126); h.extend(struct.pack('!H',n)) + else: h.append(0x80|127); h.extend(struct.pack('!Q',n)) + h.extend(mask); s.sendall(bytes(h)+bytes(b^mask[i%4] for i,b in enumerate(data))) +def ws_recv(s): + def ex(n): + o=b'' + while len(o) str: + """Detect Aw Snap / SIGILL / chrome-error / wedged renderer. Empty = healthy.""" + # 1) Tab metadata (cheap; often stale on Aw Snap — still catch obvious cases). + for tab in _cdp_fetch_tabs(instance_id): + title = str(tab.get("title") or "") + url = str(tab.get("url") or "").lower() + blob = f"{title} {url}".lower() + if "sigill" in blob: + return "sigill" + if "aw, snap" in blob or "aw snap" in blob: + return "aw_snap" + if "chrome-error://" in url or "chromewebdata" in url: + return "chrome_error" + if "status/crashed" in url or tab.get("type") == "crash": + return "tab_crashed" + # 2) Recent chrome log SIGILL (renderer crash often doesn't update tab title). + try: + if _chrome_log_recent_sigill(instance_id): + return "sigill_log" + except Exception: + pass + # 3) Real DOM / evaluate — catches Aw Snap while metadata still says Creator Studio. + try: + reason = _chrome_renderer_probe(instance_id) + except Exception: + reason = "eval_timeout" + if reason in {"sigill", "aw_snap", "chrome_error", "chrome_crash_ui", "no_ws"}: + _RENDERER_FAIL_STREAK[instance_id] = 0 + return reason + if reason in {"eval_timeout", "eval_empty", "cdp_list_fail"}: + # Studio Live tab present + wedged evaluate → heal after 2 consecutive fails. + streak = int(_RENDERER_FAIL_STREAK.get(instance_id) or 0) + 1 + _RENDERER_FAIL_STREAK[instance_id] = streak + live_tabs = False + try: + live_tabs = bool(_cdp_live_studio_urls(instance_id)) + except Exception: + live_tabs = False + # Live Studio tab + wedged evaluate is enough — metadata still looks healthy. + if live_tabs and streak >= 1: + return f"renderer_wedged_{reason}" + return "" + _RENDERER_FAIL_STREAK[instance_id] = 0 + return "" + + +def _restart_chrome_in_container(instance_id: int) -> dict[str, Any]: + """supervisorctl restart google-chrome — keeps Neko session / profile volume.""" + name = _container_name(instance_id) + # Prefer supervisor program; fall back to pkill+browser-launch supervised restart. + cmds = [ + "supervisorctl restart google-chrome", + "supervisorctl restart chromium", + ] + last = "" + for cmd in cmds: + code, out = _run(["docker", "exec", name, "bash", "-lc", cmd], timeout=45) + last = (out or "")[:240] + if code == 0: + return {"ok": True, "method": cmd, "detail": last} + # Hard fallback: kill chrome processes; supervisord autorestart=true should revive. + code, out = _run( + [ + "docker", + "exec", + name, + "bash", + "-lc", + "pkill -TERM -f '/opt/google/chrome/chrome|google-chrome|chromium' 2>/dev/null; sleep 2; " + "supervisorctl start google-chrome 2>/dev/null || supervisorctl start chromium 2>/dev/null || true; echo done", + ], + timeout=50, + ) + return {"ok": code == 0, "method": "pkill+supervisor", "detail": (out or last)[:240]} + + +def heal_unhealthy_chrome_in_nekos() -> dict[str, Any]: + """Auto-detect CDP-dead / Aw Snap / SIGILL and restart Chrome inside needed Nekos. + + Never wipes profiles. Cooldown 120s. After restart, nudge YouTube Live Studio tab. + """ + import time as _time + + ids = set(_neko_ids_needed_for_live()) + try: + ids |= set(_neko_ids_for_cdp_poll()) + except Exception: + pass + if not ids: + return {"ok": True, "checked": 0, "healed": [], "skipped": []} + now = _time.time() + healed: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + for nid in sorted(ids): + st = _container_state(nid, check_http=False) + if not st.get("running"): + skipped.append({"id": nid, "reason": "not_running"}) + continue + last = float(_CHROME_HEAL_LAST.get(nid) or 0) + if now - last < _CHROME_HEAL_COOLDOWN_SEC: + skipped.append({"id": nid, "reason": "cooldown"}) + continue + reason = "" + crash = "" + try: + crash = _chrome_tab_crash_reason(nid) + except Exception: + crash = "" + if crash: + reason = crash + elif not _devtools_version_ok(nid): + streak = int(_CDP_FAIL_STREAK.get(nid) or 0) + 1 + _CDP_FAIL_STREAK[nid] = streak + if streak < 2: + skipped.append({"id": nid, "reason": f"cdp_fail_streak_{streak}"}) + continue + reason = "cdp_dead" + else: + _CDP_FAIL_STREAK[nid] = 0 + skipped.append({"id": nid, "reason": "chrome_ok"}) + continue + _CHROME_HEAL_LAST[nid] = now + _CDP_FAIL_STREAK[nid] = 0 + _RENDERER_FAIL_STREAK[nid] = 0 + res = _restart_chrome_in_container(nid) + # Give Chrome a moment, then reopen Live control room. + _time.sleep(4.0) + nudge: dict[str, Any] = {} + try: + nudge = _cdp_nudge_live_studio_tab(nid) + except Exception as exc: + nudge = {"ok": False, "error": str(exc)[:120]} + healed.append({"id": nid, "reason": reason, "restart": res, "nudge": nudge}) + return {"ok": True, "checked": len(ids), "healed": healed, "skipped": skipped} + + +def heal_neko_runtime() -> dict[str, Any]: + """Combined soft-heal: container OOM/exit + Chrome SIGILL/Aw Snap/CDP dead.""" + a = heal_crashed_assign_nekos() + b = heal_unhealthy_chrome_in_nekos() + return { + "ok": True, + "container": a, + "chrome": b, + "healed": list(a.get("healed") or []) + list(b.get("healed") or []), + } + + def _payload_is_livestreaming(payload: dict[str, Any] | None) -> bool: body = payload or {} url = str(body.get("url") or "").lower() @@ -1311,11 +1923,23 @@ def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: text = str(body.get("text") or "").lower() signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} status = str(body.get("live_status") or "").strip().lower() - # 断播 / 待开播 are never on-air. - if status in {"encoder_lost", "stalled", "waiting", "ready", "ended", "offline", "signed_out", "streaming"}: + # 断播 / 待开播 / Preparing stream are never on-air. + if status in { + "encoder_lost", + "stalled", + "waiting", + "ready", + "ended", + "offline", + "signed_out", + "streaming", + "preparing", + }: return False if signals.get("encoder_lost") or _payload_encoder_lost(body): return False + if signals.get("preparing_stream") or "preparing stream" in text or "preparing your stream" in text: + return False if signals.get("pending_go_live") and not _payload_session_live(body): return False # Bare NODATA without an active LIVE session = 待开播. @@ -1372,18 +1996,26 @@ def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: def _payload_nodata_or_pending(payload: dict[str, Any] | None) -> bool: """True only for 待开播 / pre-go-live NODATA — never for 断播 (encoder_lost).""" body = payload or {} + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + status = str(body.get("live_status") or "").strip().lower() + text = str(body.get("text") or "").lower() + # Preparing stream can coexist with Excellent / LIVE chrome — still not ready. + if ( + status == "preparing" + or signals.get("preparing_stream") + or "preparing stream" in text + or "preparing your stream" in text + ): + return True if _payload_encoder_lost(body) or _payload_session_live(body): # Session already started: NODATA here is 断播, not 待开播. return False - signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} if signals.get("pending_go_live"): return True if signals.get("nodata"): return True - status = str(body.get("live_status") or "").strip().lower() if status in {"waiting", "ready", "signed_out", "offline"}: return True - text = str(body.get("text") or "").lower() return any( x in text for x in ( @@ -1522,17 +2154,23 @@ def _cdp_ensure_live_studio_in_container( "def is_live(u):\n" " u=(u or '').lower()\n" " return 'studio.youtube.com' in u and 'livestreaming' in u\n" + "def is_studio(u):\n" + " u=(u or '').lower()\n" + " return 'studio.youtube.com' in u\n" "try:\n" " tabs=fetch()\n" "except Exception as e:\n" " print(json.dumps({'ok':False,'error':str(e)})); raise SystemExit(0)\n" - "live=[t for t in tabs if is_live(t.get('url') or '')]\n" - "if live:\n" - " t=live[0]; tid=t.get('id')\n" + "pages=[t for t in tabs if (t.get('type') or 'page')=='page']\n" + "live=[t for t in pages if is_live(t.get('url') or '')]\n" + "studio=[t for t in pages if is_studio(t.get('url') or '')]\n" + "pick=(live or studio or [None])[0]\n" + "if pick:\n" + " tid=pick.get('id')\n" " if tid:\n" " try: urllib.request.urlopen(f'http://127.0.0.1:9222/json/activate/{tid}',timeout=2)\n" " except Exception: pass\n" - " print(json.dumps({'ok':True,'url':t.get('url',''),'action':'activate'})); raise SystemExit(0)\n" + " print(json.dumps({'ok':True,'url':pick.get('url',''),'action':'activate'})); raise SystemExit(0)\n" "q=urllib.parse.quote(WANT, safe='')\n" "try:\n" " req=urllib.request.Request('http://127.0.0.1:9222/json/new?'+q, method='PUT')\n" @@ -1753,6 +2391,29 @@ def wait_instance_ready_for_live( if last_ev and isinstance(last_ev.get("payload"), dict): live_status = str(last_ev["payload"].get("live_status") or "") health = str(last_ev["payload"].get("health") or "") + # Strict: CDP must confirm control-room chrome and NOT "Preparing stream". + # URL/telemetry settle alone still races green-loading RTMP. + control_ready = True + preparing = False + if strict: + try: + sig = _cdp_studio_page_signals(idx, max_age_sec=0.0, force=True) + except Exception: + sig = {} + if isinstance(sig, dict) and sig.get("ok"): + preparing = bool(sig.get("preparing_stream")) + control_ready = bool(sig.get("control_ready")) + if sig.get("live_status"): + live_status = str(sig.get("live_status") or live_status) + if sig.get("health"): + health = str(sig.get("health") or health) + if preparing: + # Keep waiting — never hand off to FFmpeg while preview spins. + _time.sleep(2.0) + continue + if not control_ready and live_status not in {"live", "waiting", "encoder_lost"}: + _time.sleep(2.0) + continue return { "ok": True, "id": idx, @@ -1763,6 +2424,8 @@ def wait_instance_ready_for_live( "wait_since": wait_since, "live_status": live_status, "health": health, + "control_ready": control_ready, + "preparing_stream": preparing, "url": (detect_url or last_cdp_url)[:200], "detect_source": detect_source, "note": f"live_studio_{detect_source}_settled", @@ -2303,11 +2966,17 @@ def _maybe_append_minute_report(neko_id: int, event: dict[str, Any], *, ref_key: pass +_studio_disk_write_at: float = 0.0 +_STUDIO_DISK_WRITE_MIN_INTERVAL = 2.0 + + def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: """Accept Studio telemetry from in-container Chrome extension (local or ops-neko).""" import time as _time import uuid + global _studio_disk_write_at + _bootstrap_studio_telemetry_from_disk() body = dict(payload or {}) kind, ref_key, neko_id = _resolve_neko_ref_for_payload(body) @@ -2316,9 +2985,10 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: if ref_key: body["neko_ref"] = ref_key body["neko_kind"] = kind + now = float(body.get("received_at") or _time.time()) event = { "id": str(uuid.uuid4()), - "received_at": float(body.get("received_at") or _time.time()), + "received_at": now, "neko_instance_id": neko_id, "neko_ref": ref_key, "neko_kind": kind, @@ -2334,11 +3004,15 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: _maybe_append_minute_report(neko_id, event, ref_key=f"local:{neko_id}", kind="local") if neko_id > 0: _studio_latest_by_neko[neko_id] = event - try: - path = _neko_root() / "studio_telemetry_latest.json" - path.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8") - except OSError: - pass + # Dozens of Neko tabs POST every ~1–2s; indent+rewrite of one file saturates the + # default thread pool and wedges /api/health (to_thread). Debounce disk persist. + if now - _studio_disk_write_at >= _STUDIO_DISK_WRITE_MIN_INTERVAL: + _studio_disk_write_at = now + try: + path = _neko_root() / "studio_telemetry_latest.json" + path.write_text(json.dumps(event, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + except OSError: + pass return { "ok": True, "event": { @@ -2379,6 +3053,7 @@ def studio_snapshot_for_ref( *, max_age_sec: float = 90.0, local_id: int = 0, + include_minute_reports: bool = True, ) -> dict[str, Any]: """UI snapshot by neko_ref (local:N or ops:N).""" import time as _time @@ -2410,7 +3085,11 @@ def studio_snapshot_for_ref( "received_at": 0.0, "age_sec": None, "detect_source": "", - "minute_reports": list_studio_minute_reports(nid, limit=90, neko_ref=key) if key else [], + "minute_reports": ( + list_studio_minute_reports(nid, limit=90, neko_ref=key) + if include_minute_reports and key + else [] + ), } if not key: return out @@ -2459,7 +3138,12 @@ def studio_snapshot_for_ref( return out -def studio_snapshot_for_group(group: dict[str, Any] | None, *, max_age_sec: float = 120.0) -> dict[str, Any]: +def studio_snapshot_for_group( + group: dict[str, Any] | None, + *, + max_age_sec: float = 120.0, + include_minute_reports: bool = True, +) -> dict[str, Any]: """Prefer remote ops telemetry when group opens remote Neko; else local assign Neko.""" empty = { "neko_instance_id": 0, @@ -2491,11 +3175,20 @@ def studio_snapshot_for_group(group: dict[str, Any] | None, *, max_age_sec: floa remote_snap = None if remote_bound and ops_slot > 0: - remote_snap = studio_snapshot_for_ref(f"ops:{ops_slot}", max_age_sec=max_age_sec) + remote_snap = studio_snapshot_for_ref( + f"ops:{ops_slot}", max_age_sec=max_age_sec, include_minute_reports=include_minute_reports + ) remote_snap["ui_source"] = "remote" local_snap = None if local_id > 0: - local_snap = studio_snapshot_for_instance(local_id, max_age_sec=max_age_sec) + # allow_cdp=True: use host CDP poll cache when extension ingest is quiet + # (common when neko_enabled=0 but container still running for a live push). + local_snap = studio_snapshot_for_instance( + local_id, + max_age_sec=max_age_sec, + allow_cdp=True, + include_minute_reports=include_minute_reports, + ) local_snap["neko_ref"] = f"local:{local_id}" local_snap["neko_kind"] = "local" local_snap["ui_source"] = "local" @@ -2511,19 +3204,41 @@ def studio_snapshot_for_group(group: dict[str, Any] | None, *, max_age_sec: floa except (TypeError, ValueError): return False + def _live_ui(snap: dict[str, Any] | None) -> bool: + """Studio Live control page open and/or Studio marks on-air — scrape-worthy.""" + if not isinstance(snap, dict): + return False + return bool(snap.get("live_page_open") or snap.get("on_air")) + + # Evidence-first: never let prefer=local + "fresh but page closed" hide a remote + # Live page that is actually open (UI would wrongly say「Live 页未打开」). + # neko_open_prefer still wins when BOTH sides have Live UI, or neither does. + local_fresh = _fresh(local_snap) + remote_fresh = _fresh(remote_snap) + local_live = local_fresh and _live_ui(local_snap) + remote_live = remote_fresh and _live_ui(remote_snap) + + if remote_live and not local_live: + out = dict(remote_snap or empty) + out["ui_source"] = "remote" if (prefer == "remote" and remote_bound) else "remote_fallback" + return out + if local_live and not remote_live: + out = dict(local_snap or empty) + out["ui_source"] = "local" if prefer != "remote" else "local_fallback" + return out + if prefer == "remote" and remote_bound: - if _fresh(remote_snap): + if remote_fresh: return remote_snap or empty - if _fresh(local_snap): - # Fall back to local if remote quiet + if local_fresh: out = dict(local_snap or empty) out["ui_source"] = "local_fallback" return out return remote_snap or local_snap or empty - if _fresh(local_snap): + if local_fresh: return local_snap or empty - if _fresh(remote_snap): + if remote_fresh: out = dict(remote_snap or empty) out["ui_source"] = "remote_fallback" return out @@ -2607,6 +3322,7 @@ def studio_snapshot_for_instance( *, max_age_sec: float = 90.0, allow_cdp: bool = False, + include_minute_reports: bool = True, ) -> dict[str, Any]: """UI-facing Neko Studio feedback: Live page open? On-air? Viewers? Health?""" import time as _time @@ -2630,7 +3346,9 @@ def studio_snapshot_for_instance( "age_sec": None, "detect_source": "", # ~90 pts ≈ 1.5h at 1/min — enough for Studio-style viewer timeline chart - "minute_reports": list_studio_minute_reports(nid, limit=90) if nid > 0 else [], + "minute_reports": ( + list_studio_minute_reports(nid, limit=90) if include_minute_reports and nid > 0 else [] + ), } if nid < 1: return out @@ -2672,6 +3390,18 @@ def studio_snapshot_for_instance( "detect_source": "telemetry", } ) + # Telemetry can claim live/Excellent while Studio preview still shows Preparing stream. + try: + sig = _cdp_studio_page_signals(nid, max_age_sec=90.0) + if isinstance(sig, dict) and sig.get("ok"): + if sig.get("preparing_stream") or str(sig.get("live_status") or "") == "preparing": + out["preparing_stream"] = True + out["on_air"] = False + out["live_status"] = "preparing" + if sig.get("control_ready") is not None: + out["control_ready"] = bool(sig.get("control_ready")) + except Exception: + pass return out if not allow_cdp: @@ -2684,12 +3414,19 @@ def studio_snapshot_for_instance( if st.get("running"): sig = _cdp_studio_page_signals(nid, max_age_sec=90.0) if isinstance(sig, dict) and sig.get("ok"): - on_air = bool(sig.get("on_air")) + preparing = bool(sig.get("preparing_stream")) or str(sig.get("live_status") or "") == "preparing" + on_air = bool(sig.get("on_air")) and not preparing out.update( { "live_page_open": True, "on_air": on_air, - "live_status": str(sig.get("live_status") or ("live" if on_air else "")), + "preparing_stream": preparing, + "control_ready": bool(sig.get("control_ready")), + "live_status": ( + "preparing" + if preparing + else str(sig.get("live_status") or ("live" if on_air else "")) + ), "health": str(sig.get("health") or ""), "viewer_count": sig.get("viewer_count"), "total_views": sig.get("total_views"), @@ -2795,8 +3532,11 @@ def studio_on_air_lookup(neko_id: int, *, max_age_sec: float = 120.0) -> dict[st if not snap.get("live_status"): snap["live_status"] = "live" return snap - if str(sig.get("live_status") or "") in {"waiting", "ended", "signed_out"}: + if str(sig.get("live_status") or "") in {"waiting", "ended", "signed_out", "preparing"}: snap["on_air"] = False + if str(sig.get("live_status") or "") == "preparing" or sig.get("preparing_stream"): + snap["preparing_stream"] = True + snap["live_status"] = "preparing" return snap if not vids: @@ -2841,20 +3581,32 @@ def studio_on_air_lookup(neko_id: int, *, max_age_sec: float = 120.0) -> dict[st def _neko_ids_for_cdp_poll() -> list[int]: - """Assign groups that keep a Studio Neko warm (enabled + instance id).""" + """Neko instances that should get Studio CDP backup scrapes. + + Include: + - assign groups with neko_enabled (warm Studio) + - any assign-bound instance whose container is already running + (relay may leave Chrome up while DB neko_enabled=0 — still must scrape) + """ ids: list[int] = [] try: from . import yt_assign_db for g in yt_assign_db.list_groups(include_urls=False): - if not g.get("neko_enabled"): - continue try: nid = int(g.get("neko_instance_id") or 0) except (TypeError, ValueError): nid = 0 - if nid > 0: + if nid < 1: + continue + if g.get("neko_enabled"): ids.append(nid) + continue + try: + if _container_state(nid, check_http=False).get("running"): + ids.append(nid) + except Exception: + continue except Exception: return [] return sorted(set(ids)) @@ -2920,14 +3672,16 @@ def poll_studio_cdp_once() -> dict[str, Any]: ) except Exception as exc: polled.append({"neko_instance_id": nid, "ok": False, "error": str(exc)[:160]}) - _time.sleep(1.2) + _time.sleep(0.35) return {"ok": True, "count": len(polled), "polled": polled} async def studio_cdp_poll_loop() -> None: - """Background ~55s CDP backup for Studio on-air + minute reports (extension primary).""" + """Background ~55s CDP backup for Studio on-air + soft-heal crashed needed Nekos.""" import asyncio + import logging + log = logging.getLogger("youtube_neko") if str(os.environ.get("DY_DISABLE_STUDIO_CDP_LOOP") or "").strip().lower() in {"1", "true", "yes"}: return try: @@ -2941,6 +3695,20 @@ async def studio_cdp_poll_loop() -> None: raise except Exception: pass + # Soft heal: OOM/exit containers + Chrome SIGILL/Aw Snap/CDP-dead (never wipe profiles). + if str(os.environ.get("DY_DISABLE_NEKO_SOFT_HEAL") or "").strip().lower() not in { + "1", + "true", + "yes", + }: + try: + heal = await asyncio.wait_for(asyncio.to_thread(heal_neko_runtime), timeout=180) + if heal.get("healed"): + log.warning("neko_runtime_heal %s", heal) + except asyncio.CancelledError: + raise + except Exception: + pass try: await asyncio.sleep(_CDP_POLL_INTERVAL_SEC) except asyncio.CancelledError: diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py index 708d689..c457fc8 100644 --- a/backend/app/youtube_relay_pipeline.py +++ b/backend/app/youtube_relay_pipeline.py @@ -3,6 +3,8 @@ from __future__ import annotations import asyncio +import os +import signal import time from typing import Any @@ -17,6 +19,18 @@ from .youtube_relay_presets import list_relay_quality_presets, resolve_relay_enc from .youtube_relay_status import log_age_seconds, summarize_relay_group, _key_suffix +def _ffmpeg_pid_alive(pid: int) -> bool: + """True if OS still has this pid (orphan FFmpeg after API restart).""" + p = int(pid or 0) + if p <= 0: + return False + try: + os.kill(p, 0) + return True + except OSError: + return False + + def _live_room_ids() -> set[str]: rows = db.list_live_douyin_rooms_for_shorts(limit=500) return {str(r.get("room_id") or "").strip() for r in rows if r.get("room_id")} @@ -45,9 +59,84 @@ def _group_uses_time_slot(group: dict[str, Any]) -> bool: def _group_in_active_slot(group_id: str, *, keyed_only: bool = False) -> bool: + """True when this group should push under current schedule (or timeslot test override).""" + gid = str(group_id or "").strip() + if not gid: + return False + cfg = db.get_settings_map() + if bool(cfg.get("youtube_relay_timeslot_test")): + want = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip() + if not want: + return False + if gid == want: + return True + try: + g = yt_assign_db.get_group(gid) + w = yt_assign_db.get_group(want) + if g and w and yt_assign_db.same_yt_channel(g, w): + return True + except Exception: + pass + return False return yt_assign_db.group_in_rotation_slot(group_id, keyed_only=keyed_only) +def _timeslot_test_channels() -> list[dict[str, Any]]: + sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) + return [c for c in (sched.get("channels") or []) if str(c.get("group_id") or "").strip()] + + +def _pick_default_timeslot_test_group_id(channels: list[dict[str, Any]] | None = None) -> str: + rows = channels if channels is not None else _timeslot_test_channels() + if not rows: + return "" + active = next((c for c in rows if c.get("active")), None) + pick = active or rows[0] + return str(pick.get("group_id") or "").strip() + + +def _group_has_stream_key(group: dict[str, Any]) -> bool: + return bool(str(group.get("stream_key") or "").strip() or group.get("has_stream_key")) + + +def _normal_auto_candidates(groups: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Enabled non-time_slot groups with a live KEY (auto when 时间段排班 off).""" + out: list[dict[str, Any]] = [] + for g in groups: + if not g.get("enabled"): + continue + if _group_uses_time_slot(g): + continue + if not _group_has_stream_key(g): + continue + out.append(g) + return out + + +def _claim_first_live_normal( + groups: list[dict[str, Any]], +) -> tuple[str, dict[str, Any], dict[str, str]] | None: + """Exclusive normal mode: claim the first group whose 直播地址列表 has a live room. + + Deterministic order: sort_order, then group id. Sticky winner is handled by caller. + """ + live_ids = _live_room_ids() + ranked: list[tuple[int, str, dict[str, Any], dict[str, str]]] = [] + for g in groups: + src = pick_source_for_group(g, respect_schedule=False) + if not src: + continue + rid = str(src.get("room_id") or "").strip() + if not rid or rid not in live_ids: + continue + ranked.append((int(g.get("sort_order") or 0), str(g.get("id") or ""), g, src)) + if not ranked: + return None + ranked.sort(key=lambda x: (x[0], x[1])) + _ord, gid, g, src = ranked[0] + return gid, g, src + + def pick_source_for_group( group: dict[str, Any], *, @@ -60,7 +149,7 @@ def pick_source_for_group( """Choose Douyin source. - 时间段分类: only when group is in active 24/N slot; source = currently-live monitor rooms. - - 普通分类: featured list (prefer live), optionally gated by schedule. + - 普通分类: 直播地址列表 / featured (prefer live), optionally gated by schedule. ``time_slot_mode`` kept for API compatibility; per-group ``category`` is authoritative. ``exclude_room_ids`` skips rooms already probed offline this tick (time_slot sticky-lag). @@ -153,11 +242,45 @@ class YoutubeRelayPipeline: self._neko_paused_instances: set[int] = set() # Serialize start/restart per group — prevents double FFmpeg on same stream key. self._group_locks: dict[str, asyncio.Lock] = {} + # Consecutive Studio-not-on-air kills → cooldown (stops flap + daily stream burn). + self._studio_fail_times: dict[str, list[float]] = {} + self._studio_cooldown_until: dict[str, float] = {} self.last_error = "" self.processed = 0 self._status_cache: dict[str, Any] | None = None self._status_cache_at = 0.0 - self._STATUS_CACHE_TTL_SEC = 1.0 + self._STATUS_CACHE_TTL_SEC = 5.0 + + def _studio_cooldown_active(self, gid: str) -> float: + until = float(self._studio_cooldown_until.get(gid) or 0) + if until <= time.time(): + self._studio_cooldown_until.pop(gid, None) + return 0.0 + return until + + def _clear_studio_cooldown(self, gid: str) -> None: + self._studio_cooldown_until.pop(gid, None) + self._studio_fail_times.pop(gid, None) + + def _note_studio_not_on_air(self, gid: str) -> tuple[bool, str]: + """Record a Studio-not-on-air kill. Returns (tripped, message).""" + now = time.time() + window = 30 * 60.0 + need = 3 + cooldown = 6 * 3600.0 + times = [t for t in self._studio_fail_times.get(gid, []) if now - t <= window] + times.append(now) + self._studio_fail_times[gid] = times + if len(times) < need: + return False, "" + self._studio_cooldown_until[gid] = now + cooldown + self._studio_fail_times[gid] = [] + hrs = int(cooldown // 3600) + msg = ( + f"Studio 连续 {need} 次推流后仍未 on_air(常见:YouTube daily stream limit / 待开播卡死)," + f"已熔断自动重试 {hrs} 小时,避免反复开停烧额度。手动「开始」可解除。" + ) + return True, msg def status(self) -> dict[str, Any]: now = time.time() @@ -193,6 +316,11 @@ class YoutubeRelayPipeline: st = dict(states.get(gid) or {}) sess = self._sessions.get(gid) running = bool(sess and sess.stats.running) + orphan_pid = int(st.get("ffmpeg_pid") or 0) + orphan_alive = (not running) and _ffmpeg_pid_alive(orphan_pid) + # After API restart, in-memory session is gone but FFmpeg may still push — + # treat pid-alive as running so UI stays 推流中 / 启动中 (not 监听中 flap). + effective_running = running or orphan_alive recent_log = list( sess.stats.recent_log if sess else youtube_relay_db._parse_recent_log(st.get("recent_log")) ) @@ -201,7 +329,7 @@ class YoutubeRelayPipeline: monitor = summarize_relay_group( group=g, st=st, - session_running=running, + session_running=effective_running, pipeline_enabled=pipeline_enabled or gid in self._manual_hold, log_age_seconds=log_age_seconds(st, now), lane_armed=gid in self._manual_hold or pipeline_enabled, @@ -214,15 +342,19 @@ class YoutubeRelayPipeline: raw_st = str(st.get("status") or "").lower() armed = gid in self._manual_hold or pipeline_enabled if not receiving and not running and raw_st in {"pushing", "streaming", "starting"}: - youtube_relay_db.upsert_relay_state( - gid, - status="idle", - ffmpeg_pid=0, - speed=0, - frame=0, - error="", - recent_log=st.get("recent_log") or [], - ) + if orphan_alive: + # Keep DB status; ensure path will reuse orphan instead of idle→start flap. + pass + else: + youtube_relay_db.upsert_relay_state( + gid, + status="idle", + ffmpeg_pid=0, + speed=0, + frame=0, + error="", + recent_log=st.get("recent_log") or [], + ) elif not receiving: err = str(st.get("error") or "") raw_st2 = str(st.get("status") or "").lower() @@ -318,9 +450,13 @@ class YoutubeRelayPipeline: "pushing" if receiving else ( - "idle" - if raw_st in {"pushing", "streaming", "starting"} - else str(st.get("status") or "idle") + (raw_st if raw_st in {"pushing", "streaming", "starting"} else "pushing") + if effective_running + else ( + "idle" + if raw_st in {"pushing", "streaming", "starting"} + else str(st.get("status") or "idle") + ) ) ), "error": st.get("error") or "", @@ -368,6 +504,10 @@ class YoutubeRelayPipeline: "youtube_relay_quality_presets": list_relay_quality_presets(active_id=preset_id), "youtube_relay_exclusive_live": bool(cfg.get("youtube_relay_exclusive_live", True)), "youtube_relay_time_slot_mode": bool(cfg.get("youtube_relay_time_slot_mode")), + "youtube_relay_timeslot_test": bool(cfg.get("youtube_relay_timeslot_test")), + "youtube_relay_timeslot_test_group_id": str( + cfg.get("youtube_relay_timeslot_test_group_id") or "" + ).strip(), "youtube_relay_timeslot_exclude_count": 0, }, "groups": relay_groups, @@ -376,6 +516,15 @@ class YoutubeRelayPipeline: "neko_paused_instances": sorted(self._neko_paused_instances), "studio_live": None, } + try: + if bool(cfg.get("youtube_relay_timeslot_test")): + payload["schedule"] = yt_assign_db.overlay_timeslot_test_schedule( + schedule, + test_on=True, + test_group_id=str(cfg.get("youtube_relay_timeslot_test_group_id") or ""), + ) + except Exception: + pass try: payload["settings"]["youtube_relay_timeslot_exclude_count"] = len( yt_assign_db.timeslot_exclude_room_ids(include_manual_featured=True) @@ -451,6 +600,7 @@ class YoutubeRelayPipeline: # Exclusive FFmpeg/Neko lock applies only when push actually starts (see _ensure_group_relay). await self.start() self._manual_hold.add(gid) + self._clear_studio_cooldown(gid) # 时间段: keep schedule gate so only the active slot winner pushes. # 普通: manual Start ignores schedule window (force lane). respect = True if group_slot else False @@ -470,11 +620,76 @@ class YoutubeRelayPipeline: youtube_relay_db.clear_relay_state(gid, status="stopped") await asyncio.to_thread(relay_sessions.end_session, gid, reason=reason) + async def _graceful_retire_group( + self, + group: dict[str, Any] | None, + *, + reason: str, + stop_neko: bool = True, + was_pushing: bool | None = None, + ) -> dict[str, Any]: + """Stop FFmpeg → Studio End Stream (CDP / API) → optional Neko stop. + + Avoid hard-killing Neko while YouTube still thinks the broadcast is LIVE. + """ + from . import youtube_neko + + g = group or {} + gid = str(g.get("id") or "").strip() + neko_id = int(g.get("neko_instance_id") or 0) + channel_pk = str(g.get("channel_pk") or "").strip() + pushing = bool(was_pushing) if was_pushing is not None else (gid in self._sessions) + if gid: + await self._halt_session(gid, reason=reason) + end_res: dict[str, Any] = {"skipped": True} + neko_up = False + if neko_id > 0: + try: + neko_up = bool( + (await asyncio.to_thread(youtube_neko._container_state, neko_id, check_http=False)).get( + "running" + ) + ) + except Exception: + neko_up = False + # If Neko is still up and we are retiring the lane, try End Stream even when FFmpeg + # already died — Studio may still show LIVE + End Stream. + if neko_up and (pushing or stop_neko): + try: + end_res = await asyncio.to_thread( + youtube_neko.end_live_session, + neko_id, + channel_pk=channel_pk, + wait_encoder_lost_sec=12.0 if pushing else 4.0, + settle_sec=3.0, + ) + except Exception as exc: + end_res = {"ok": False, "error": str(exc)[:200]} + if gid: + youtube_relay_db.upsert_relay_state( + gid, + status="ending", + error="", + recent_log=[ + f"[relay] graceful_end reason={reason} ok={str(end_res.get('ok'))}" + ], + ) + stop_res: dict[str, Any] = {"skipped": True} + if stop_neko and neko_id > 0: + stop_res = await asyncio.to_thread(youtube_neko.stop_instance, neko_id) + return {"ok": True, "group_id": gid, "end": end_res, "neko_stop": stop_res} + async def stop_group(self, group_id: str) -> dict[str, Any]: gid = str(group_id or "").strip() was_exclusive = gid == self._exclusive_winner self._manual_hold.discard(gid) - await self._halt_session(gid, reason="stopped") + g = yt_assign_db.get_group(gid) or {"id": gid} + exclusive_on = bool(db.get_settings_map().get("youtube_relay_exclusive_live", True)) + await self._graceful_retire_group( + g, + reason="stopped", + stop_neko=bool(was_exclusive and exclusive_on), + ) if was_exclusive: await self._release_exclusive_live() return {"ok": True, "group_id": gid} @@ -517,9 +732,12 @@ class YoutubeRelayPipeline: """sh2 outer monitor: forever poll armed lanes; offline never exits the lane.""" while not self._stop.is_set(): try: - cfg = db.get_settings_map() + # Heavy SQLite scans off the asyncio loop so /api/health stays responsive. + def _tick_inputs() -> tuple[dict[str, Any], list[dict[str, Any]]]: + return db.get_settings_map(), yt_assign_db.list_groups(include_urls=True) + + cfg, groups = await asyncio.to_thread(_tick_inputs) auto_on = bool(cfg.get("youtube_relay_enabled")) - groups = yt_assign_db.list_groups(include_urls=True) by_id = {str(g.get("id") or ""): g for g in groups} active_ids: set[str] = set() @@ -539,104 +757,307 @@ class YoutubeRelayPipeline: g, force=False, respect_schedule=hold_respect, cfg=cfg ) - # 2) Auto relay: 时间段 groups via 24/N; 普通 = 手动 only (skip auto). + # 2) Auto relay + # - 时间段排班 ON: 24/N for category=time_slot (源=监控在播抖音) + # - 时间段排班 OFF: all 普通 groups watch 直播地址列表; exclusive → first-live sticky if auto_on: from . import youtube_neko - slot_winner_gid = "" - slot_winner_g: dict[str, Any] | None = None + time_slot_mode_on = bool(cfg.get("youtube_relay_time_slot_mode")) + exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True)) time_slot_groups = [g for g in groups if _group_uses_time_slot(g)] - run_slot_auto = bool(time_slot_groups) - if run_slot_auto: - sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) - active_ch = next((c for c in sched.get("channels") or [] if c.get("active")), None) - if active_ch: - candidate_ids = [str(active_ch.get("group_id") or "")] - candidate_ids.extend(str(x) for x in (active_ch.get("alias_group_ids") or []) if x) - candidate_ids = [g for g in candidate_ids if g and by_id.get(g)] - for gid0 in candidate_ids: - sess = self._sessions.get(gid0) - if sess and sess.stats.running: - slot_winner_gid = gid0 - slot_winner_g = by_id.get(gid0) - break - if not slot_winner_gid and candidate_ids: - slot_winner_gid = candidate_ids[0] - slot_winner_g = by_id.get(slot_winner_gid) + run_slot_auto = bool(time_slot_mode_on and time_slot_groups) - for g in groups: - gid = str(g.get("id") or "") - if not gid or not g.get("enabled"): - continue - if gid in active_ids: - continue - if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"): - continue - # 普通分类:仅手动推流,不走自动排班。 - if not _group_uses_time_slot(g): - continue - # 时间段:非当前时段 → 停推流;仅在「单频道独占」时顺带停 Neko。 - if run_slot_auto and gid != slot_winner_gid: - exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True)) - same_channel_as_winner = bool( - slot_winner_g and yt_assign_db.same_yt_channel(g, slot_winner_g) + if time_slot_mode_on and not time_slot_groups: + # 排班开但无可用「时间段」频道:禁止落入普通自动,避免与 UI 矛盾。 + for g in _normal_auto_candidates(groups): + gid = str(g.get("id") or "") + if not gid or gid in self._manual_hold: + continue + if gid in self._sessions: + await self._halt_session( + gid, reason="timeslot_mode_no_slot_groups" + ) + youtube_relay_db.upsert_relay_state( + gid, + status="idle", + error=( + "时间段排班已开,但没有可用的「时间段」分类频道" + "(需 KEY + 分类=时间段)" + ), + recent_log=[ + "[relay] time_slot_mode on but no time_slot groups" + ], ) - in_active_slot = _group_in_active_slot(gid, keyed_only=True) - if same_channel_as_winner and in_active_slot: - if gid in self._sessions: - await self._halt_session(gid, reason="duplicate_channel_key") - neko_id = int(g.get("neko_instance_id") or 0) - if exclusive_on and neko_id > 0: - await asyncio.to_thread(youtube_neko.stop_instance, neko_id) + elif run_slot_auto: + slot_winner_gid = "" + slot_winner_g: dict[str, Any] | None = None + test_on = bool(cfg.get("youtube_relay_timeslot_test")) + test_gid = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip() + if test_on: + if test_gid and by_id.get(test_gid): + slot_winner_gid = test_gid + slot_winner_g = by_id.get(test_gid) + else: + fallback = _pick_default_timeslot_test_group_id() + if fallback and by_id.get(fallback): + slot_winner_gid = fallback + slot_winner_g = by_id.get(fallback) + if fallback != test_gid: + db.update_settings_map( + {"youtube_relay_timeslot_test_group_id": fallback} + ) + else: + sched = yt_assign_db.build_rotation_schedule( + include_urls=False, keyed_only=True + ) + active_ch = next( + (c for c in sched.get("channels") or [] if c.get("active")), None + ) + if active_ch: + candidate_ids = [str(active_ch.get("group_id") or "")] + candidate_ids.extend( + str(x) for x in (active_ch.get("alias_group_ids") or []) if x + ) + candidate_ids = [g for g in candidate_ids if g and by_id.get(g)] + for gid0 in candidate_ids: + sess = self._sessions.get(gid0) + if sess and sess.stats.running: + slot_winner_gid = gid0 + slot_winner_g = by_id.get(gid0) + break + if not slot_winner_gid and candidate_ids: + slot_winner_gid = candidate_ids[0] + slot_winner_g = by_id.get(slot_winner_gid) + + for g in groups: + gid = str(g.get("id") or "") + if not gid or not g.get("enabled"): + continue + if gid in active_ids: + continue + if not _group_has_stream_key(g): + continue + # 普通分类:时段排班开启时不走自动(仅手动 hold) + if not _group_uses_time_slot(g): + continue + if gid != slot_winner_gid: + same_channel_as_winner = bool( + slot_winner_g and yt_assign_db.same_yt_channel(g, slot_winner_g) + ) + in_active_slot = _group_in_active_slot(gid, keyed_only=True) + if same_channel_as_winner and in_active_slot: + await self._graceful_retire_group( + g, + reason="duplicate_channel_key", + stop_neko=exclusive_on, + ) + youtube_relay_db.upsert_relay_state( + gid, + status="paused_exclusive", + error=f"同频道备用 KEY:当前由 {slot_winner_g.get('name') if slot_winner_g else slot_winner_gid} 推流", + recent_log=["[relay] duplicate_yt_channel — paused"], + ) + continue + if not in_active_slot: + await self._graceful_retire_group( + g, + reason="outside_slot", + stop_neko=exclusive_on, + ) + youtube_relay_db.upsert_relay_state( + gid, + status="outside_slot", + error="", + recent_log=["[relay] outside_slot — waiting schedule window"], + ) + continue + continue + cool_until = self._studio_cooldown_active(gid) + if cool_until > 0: + left = int(max(0, cool_until - time.time())) + youtube_relay_db.upsert_relay_state( + gid, + status="paused_studio", + error=( + f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。" + f"常见原因:YouTube daily stream limit。手动「开始」可解除。" + ), + recent_log=["[relay] studio_cooldown — skip auto"], + ) + continue + src = pick_source_for_group( + g, + respect_schedule=True, + prefer_room_id=str( + (youtube_relay_db.get_relay_state(gid) or {}).get("source_room_id") + or "" + ), + prefer_source_url=str( + (youtube_relay_db.get_relay_state(gid) or {}).get("source_url") or "" + ), + ) + if not src: + sess = self._sessions.get(gid) + if sess and sess.stats.running: + active_ids.add(gid) + continue + if gid in self._sessions and gid not in self._manual_hold: + await self._halt_session(gid, reason="no_live_source") + youtube_relay_db.upsert_relay_state( + gid, + status="waiting", + error="时间段模式:等待在播抖音源", + recent_log=["[relay] waiting live Douyin source"], + ) + if slot_winner_g and gid == slot_winner_gid: + await self._enforce_exclusive_live(gid, slot_winner_g) + continue + active_ids.add(gid) + await self._ensure_group_relay( + g, source=src, cfg=cfg, respect_schedule=True + ) + else: + # 时间段排班关闭:普通频道自动监听直播地址列表 + # Stop leftover time_slot auto sessions (manual hold kept). + for g in time_slot_groups: + gid = str(g.get("id") or "") + if not gid or gid in self._manual_hold: + continue + if gid in self._sessions: + await self._halt_session(gid, reason="timeslot_mode_off") + + normal_groups = _normal_auto_candidates(groups) + winner_gid = "" + winner_g: dict[str, Any] | None = None + winner_src: dict[str, str] | None = None + + if exclusive_on: + cur = str(self._exclusive_winner or "").strip() + cur_g = by_id.get(cur) if cur else None + if ( + cur_g + and cur_g.get("enabled") + and not _group_uses_time_slot(cur_g) + and _group_has_stream_key(cur_g) + ): + sticky_src = pick_source_for_group(cur_g, respect_schedule=False) + live_ids = _live_room_ids() + sticky_live = bool( + sticky_src + and str(sticky_src.get("room_id") or "").strip() in live_ids + ) + sess = self._sessions.get(cur) + still_pushing = bool(sess and sess.stats.running) + if sticky_live or still_pushing or cur in self._manual_hold: + winner_gid = cur + winner_g = cur_g + winner_src = sticky_src if sticky_live else None + else: + # 真正停播:无在播源且未在推 → 进入下一轮 + self._exclusive_winner = None + await self._release_exclusive_live() + + if not winner_gid: + claimed = _claim_first_live_normal(normal_groups) + if claimed: + winner_gid, winner_g, winner_src = claimed + + for g in normal_groups: + gid = str(g.get("id") or "") + if not gid or gid in active_ids: + continue + if exclusive_on and winner_gid and gid != winner_gid: + await self._graceful_retire_group( + g, reason="exclusive_live", stop_neko=True + ) youtube_relay_db.upsert_relay_state( gid, status="paused_exclusive", - error=f"同频道备用 KEY:当前由 {slot_winner_g.get('name') if slot_winner_g else slot_winner_gid} 推流", - recent_log=["[relay] duplicate_yt_channel — paused"], + error=( + f"单路独占:当前仅允许 " + f"{(winner_g or {}).get('name') or winner_gid} 推流" + ), + recent_log=[ + f"[relay] exclusive_live winner={winner_gid} — paused" + ], ) continue - if not in_active_slot: - if gid in self._sessions: - await self._halt_session(gid, reason="outside_slot") - neko_id = int(g.get("neko_instance_id") or 0) - if exclusive_on and neko_id > 0: - await asyncio.to_thread(youtube_neko.stop_instance, neko_id) + if exclusive_on and not winner_gid: youtube_relay_db.upsert_relay_state( gid, - status="outside_slot", - error="", - recent_log=["[relay] outside_slot — waiting schedule window"], + status="waiting", + error="自动推流:等待直播地址列表中的房间开播", + recent_log=["[relay] waiting featured live (exclusive)"], ) continue - continue - src = pick_source_for_group( - g, - respect_schedule=True, - prefer_room_id=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_room_id") or ""), - prefer_source_url=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_url") or ""), - ) - if not src: - sess = self._sessions.get(gid) - if sess and sess.stats.running: - active_ids.add(gid) + + cool_until = self._studio_cooldown_active(gid) + if cool_until > 0: + left = int(max(0, cool_until - time.time())) + youtube_relay_db.upsert_relay_state( + gid, + status="paused_studio", + error=( + f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。" + f"常见原因:YouTube daily stream limit。手动「开始」可解除。" + ), + recent_log=["[relay] studio_cooldown — skip auto"], + ) continue - # Outside schedule / empty list — idle, do not kill manual holds. - if gid in self._sessions and gid not in self._manual_hold: - await self._halt_session(gid, reason="no_live_source") - youtube_relay_db.upsert_relay_state( - gid, - status="waiting", - error="时间段模式:等待在播抖音源", - recent_log=["[relay] waiting live Douyin source"], + + # Exclusive sticky: keep running FFmpeg while source flaps offline briefly. + if exclusive_on and gid == winner_gid and not winner_src: + sess = self._sessions.get(gid) + if sess and sess.stats.running: + active_ids.add(gid) + continue + + src = ( + winner_src + if exclusive_on and gid == winner_gid and winner_src + else pick_source_for_group( + g, + respect_schedule=False, + prefer_room_id=str( + (youtube_relay_db.get_relay_state(gid) or {}).get( + "source_room_id" + ) + or "" + ), + prefer_source_url=str( + (youtube_relay_db.get_relay_state(gid) or {}).get( + "source_url" + ) + or "" + ), + ) + ) + if src: + live_ids = _live_room_ids() + rid = str(src.get("room_id") or "").strip() + if not rid or rid not in live_ids: + src = None + if not src: + sess = self._sessions.get(gid) + if sess and sess.stats.running: + active_ids.add(gid) + continue + if gid in self._sessions and gid not in self._manual_hold: + await self._halt_session(gid, reason="no_live_source") + youtube_relay_db.upsert_relay_state( + gid, + status="waiting", + error="自动推流:等待直播地址列表中的房间开播", + recent_log=["[relay] waiting featured live"], + ) + if exclusive_on and winner_g and gid == winner_gid: + await self._enforce_exclusive_live(gid, winner_g) + continue + active_ids.add(gid) + await self._ensure_group_relay( + g, source=src, cfg=cfg, respect_schedule=False ) - # Keep winner Neko warm while waiting for a live room. - if slot_winner_g and gid == slot_winner_gid: - await self._enforce_exclusive_live(gid, slot_winner_g) - continue - active_ids.add(gid) - await self._ensure_group_relay( - g, source=src, cfg=cfg, respect_schedule=True - ) else: # Auto off: stop non-manual ffmpeg sessions only. for gid in list(self._sessions.keys()): @@ -665,18 +1086,112 @@ class YoutubeRelayPipeline: async def set_time_slot_mode(self, enabled: bool) -> dict[str, Any]: """Enable 24/N keyed-channel slots + live Douyin sources. - Does NOT force exclusive Neko/FFmpeg — operators on physical hosts may - keep multiple Studios warm. Does NOT turn on 自动推流. + When OFF + 自动推流 ON: normal groups auto-watch 直播地址列表 instead. + Does NOT force exclusive Neko/FFmpeg. Does NOT turn on 自动推流. """ on = bool(enabled) patch: dict[str, Any] = {"youtube_relay_time_slot_mode": on} if on: patch["youtube_relay_respect_schedule"] = True + else: + # Real schedule off ⇒ drop test override too. + patch["youtube_relay_timeslot_test"] = False + patch["youtube_relay_timeslot_test_group_id"] = "" db.update_settings_map(patch) self._status_cache = None self._status_cache_at = 0.0 return await asyncio.to_thread(self.status) + async def set_timeslot_test_mode(self, enabled: bool) -> dict[str, Any]: + """Force time_slot winner by operator (ignore Beijing 24/N clock) for quick tests.""" + on = bool(enabled) + channels = _timeslot_test_channels() + if on and not channels: + raise ValueError("没有可测试的时间段频道(需:时间段分类 + KEY + 排班开关)") + patch: dict[str, Any] = {"youtube_relay_timeslot_test": on} + if on: + cur = str(db.get_settings_map().get("youtube_relay_timeslot_test_group_id") or "").strip() + ids = {str(c.get("group_id") or "") for c in channels} + if cur not in ids: + patch["youtube_relay_timeslot_test_group_id"] = _pick_default_timeslot_test_group_id( + channels + ) + patch["youtube_relay_enabled"] = True + patch["youtube_relay_respect_schedule"] = True + else: + patch["youtube_relay_timeslot_test_group_id"] = "" + db.update_settings_map(patch) + self._status_cache = None + self._status_cache_at = 0.0 + if on: + await self.start() + await self._kick_timeslot_test_winner() + return await asyncio.to_thread(self.status) + + async def timeslot_test_next(self) -> dict[str, Any]: + """Advance forced test winner to the next time_slot channel (wrap around).""" + channels = _timeslot_test_channels() + if not channels: + raise ValueError("没有可测试的时间段频道(需:时间段分类 + KEY + 排班开关)") + ids = [str(c.get("group_id") or "").strip() for c in channels if str(c.get("group_id") or "").strip()] + cfg = db.get_settings_map() + cur = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip() + if cur in ids: + nxt = ids[(ids.index(cur) + 1) % len(ids)] + else: + # First click: jump to the channel after the real-clock active slot. + active_i = next((i for i, c in enumerate(channels) if c.get("active")), -1) + nxt = ids[(active_i + 1) % len(ids)] if active_i >= 0 else ids[0] + name = next( + (str(c.get("name") or "") for c in channels if str(c.get("group_id") or "") == nxt), + nxt, + ) + db.update_settings_map( + { + "youtube_relay_timeslot_test": True, + "youtube_relay_timeslot_test_group_id": nxt, + "youtube_relay_enabled": True, + "youtube_relay_respect_schedule": True, + } + ) + self._status_cache = None + self._status_cache_at = 0.0 + await self.start() + await self._kick_timeslot_test_winner() + st = await asyncio.to_thread(self.status) + st["timeslot_test_next"] = {"group_id": nxt, "name": name} + return st + + async def _kick_timeslot_test_winner(self) -> None: + """Switch exclusive Neko to forced winner; FFmpeg starts on next pipeline tick. + + Avoid blocking the HTTP request on Studio settle / stream resolve (can take minutes). + Still gracefully End Stream on the previous winner before stopping its Neko. + """ + cfg = db.get_settings_map() + gid = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip() + if not gid: + return + group = yt_assign_db.get_group(gid) + if not group or not group.get("enabled"): + return + for other in list(self._sessions.keys()): + if other != gid: + self._manual_hold.discard(other) + og = yt_assign_db.get_group(other) or {"id": other} + await self._graceful_retire_group( + og, + reason="timeslot_test_rotate", + stop_neko=bool(cfg.get("youtube_relay_exclusive_live", True)), + ) + await self._enforce_exclusive_live(gid, group) + youtube_relay_db.upsert_relay_state( + gid, + status="starting", + error="", + recent_log=["[relay] timeslot_test — winner set, waiting auto tick for push"], + ) + async def _enforce_exclusive_live(self, winner_gid: str, winner_group: dict[str, Any]) -> None: """When one channel actually pushes: stop other FFmpeg + Neko; keep winner Neko up.""" cfg = db.get_settings_map() @@ -693,8 +1208,7 @@ class YoutubeRelayPipeline: if not gid or gid == winner_gid: continue self._manual_hold.discard(gid) - if gid in self._sessions: - await self._halt_session(gid, reason="exclusive_live") + await self._graceful_retire_group(g, reason="exclusive_live", stop_neko=True) youtube_relay_db.upsert_relay_state( gid, status="paused_exclusive", @@ -704,6 +1218,7 @@ class YoutubeRelayPipeline: from . import youtube_neko + # Any leftover Nekos (never pushed / already halted) still stop for RAM. paused = await asyncio.to_thread(youtube_neko.stop_instances_except, winner_neko) self._neko_paused_instances |= set(paused) prefer = str(winner_group.get("neko_open_prefer") or "local").strip().lower() @@ -733,6 +1248,20 @@ class YoutubeRelayPipeline: sess = self._sessions.get(gid) if sess and sess.stats.running: return + # Normal exclusive sticky: keep claim while 直播地址列表 still has live rooms. + try: + g = next( + ( + x + for x in yt_assign_db.list_groups(include_urls=True) + if str(x.get("id") or "") == gid + ), + None, + ) + except Exception: + g = None + if g and not _group_uses_time_slot(g) and pick_source_for_group(g, respect_schedule=False): + return await self._release_exclusive_live() async def _ensure_group_relay( @@ -745,6 +1274,21 @@ class YoutubeRelayPipeline: respect_schedule: bool | None = None, ) -> dict[str, Any]: gid = str(group.get("id") or "") + if not force: + cool_until = self._studio_cooldown_active(gid) + if cool_until > 0: + left = int(max(0, cool_until - time.time())) + err = ( + f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。" + f"常见原因:YouTube daily stream limit。手动「开始」可解除。" + ) + youtube_relay_db.upsert_relay_state( + gid, + status="paused_studio", + error=err, + recent_log=["[relay] studio_cooldown — skip ensure"], + ) + return {"ok": False, "error": err, "fatal": False} lock = self._group_locks.setdefault(gid, asyncio.Lock()) async with lock: return await self._ensure_group_relay_locked( @@ -801,7 +1345,11 @@ class YoutubeRelayPipeline: prefer_source_url=prefer_url, ) if any_src and respect_schedule: - err = "当前不在分配时段,自动推流已跳过(手动「开始」可强制监听)" + # 时间段分类:手动「开始」也不绕过 24/N 窗口(见 start_group)。 + if slot_mode: + err = "当前不在分配时段(时间段频道受 24/N 窗口限制,需等到本频道轮播窗口)" + else: + err = "当前不在分配时段,自动推流已跳过" fatal = False elif slot_mode: err = "时间段模式:当前没有在播的抖音直播间可作为推流源" @@ -838,6 +1386,33 @@ class YoutubeRelayPipeline: # Dead/stale session (CDN 404 etc.) → drop and re-resolve FLV URL. await self._halt_session(gid, reason="restart" if force else "stream_refresh") + # Orphan FFmpeg (API restart lost _sessions): reuse or kill — never start a second push. + orphan_pid = int(relay_st.get("ffmpeg_pid") or 0) + if _ffmpeg_pid_alive(orphan_pid) and not (self._sessions.get(gid) and self._sessions[gid].stats.running): + if not force: + orphan_logs = youtube_relay_db._parse_recent_log(relay_st.get("recent_log")) + if not orphan_logs: + orphan_logs = [f"[relay] reused orphan ffmpeg pid={orphan_pid}"] + youtube_relay_db.upsert_relay_state( + gid, + status="pushing", + ffmpeg_pid=orphan_pid, + error="", + recent_log=orphan_logs[-40:], + ) + return { + "ok": True, + "group_id": gid, + "reused_orphan": True, + "ffmpeg_pid": orphan_pid, + } + try: + os.kill(orphan_pid, signal.SIGTERM) + except OSError: + pass + await asyncio.sleep(1.2) + youtube_relay_db.upsert_relay_state(gid, ffmpeg_pid=0) + if force: self._manual_hold.add(gid) @@ -1193,8 +1768,9 @@ class YoutubeRelayPipeline: on_air = bool(snap.get("on_air")) live_status = str(snap.get("live_status") or "").strip().lower() page_open = bool(snap.get("live_page_open")) - # 待开播 only — never treat 断播(encoder_lost) as invalid-push kill. - pending = live_status in {"waiting", "ready", "signed_out", "offline"} + preparing = live_status == "preparing" or bool(snap.get("preparing_stream")) + # 待开播 / Preparing stream — never treat 断播(encoder_lost) as invalid-push kill. + pending = live_status in {"waiting", "ready", "signed_out", "offline", "preparing"} try: payload_probe = { "live_status": live_status, @@ -1205,31 +1781,43 @@ class YoutubeRelayPipeline: "nodata": live_status == "waiting", "encoder_lost": live_status in {"encoder_lost", "stalled"}, "session_live": live_status in {"live", "encoder_lost", "stalled"}, - "pending_go_live": pending, + "pending_go_live": pending and not preparing, + "preparing_stream": preparing, }, } - if _yn._payload_encoder_lost(payload_probe) or live_status in { + if preparing: + pending = True + elif _yn._payload_encoder_lost(payload_probe) or live_status in { "encoder_lost", "stalled", }: pending = False - if not _yn._payload_nodata_or_pending(payload_probe): + elif not _yn._payload_nodata_or_pending(payload_probe): pending = False except Exception: - pass + if preparing: + pending = True + # Preparing stream + Excellent = invalid green-loading push — kill sooner. + prep_deadline = min(on_air_deadline, 45.0) + kill_prep = preparing and push_sec >= prep_deadline # Only act on fresh evidence of 待开播 — never kill on 断播 / missing telemetry. - if fresh and page_open and (not on_air) and pending: + if fresh and page_open and (not on_air) and (pending or kill_prep): + why = "Preparing stream(预览未就绪)" if preparing else (live_status or "待开播/NODATA") err = ( - f"Studio 仍为 {live_status or '待开播/NODATA'}(未 on_air)," + f"Studio 仍为 {why}(未 on_air)," f"推流已 {int(push_sec)}s — 判定无效推流,已自动停止" ) boot = list(sess.stats.recent_log or []) boot.append(f"[relay] {err}") await asyncio.to_thread(sess.stop) self._sessions.pop(gid, None) + tripped, cool_msg = self._note_studio_not_on_air(gid) + if tripped: + err = cool_msg + boot.append(f"[relay] {cool_msg}") youtube_relay_db.upsert_relay_state( gid, - status="waiting", + status="paused_studio" if tripped else "waiting", ffmpeg_pid=0, speed=0, frame=0, @@ -1275,5 +1863,78 @@ class YoutubeRelayPipeline: await asyncio.to_thread(relay_sessions.end_session, gid, reason="stream_refresh") await self._maybe_release_exclusive_live() + # Orphan FFmpeg (API restart left OS pid alive, no in-memory session) still needs + # the Studio on_air watchdog — otherwise green-loading can burn for hours. + if _yn is not None: + try: + for st_row in youtube_relay_db.list_relay_states(): + gid = str(st_row.get("group_id") or "").strip() + if not gid or gid in self._sessions: + continue + if str(st_row.get("status") or "") not in {"pushing", "starting"}: + continue + try: + orphan_pid = int(st_row.get("ffmpeg_pid") or 0) + except (TypeError, ValueError): + orphan_pid = 0 + if orphan_pid < 1 or not _ffmpeg_pid_alive(orphan_pid): + continue + started = float(st_row.get("started_at") or now) + push_sec = max(0.0, now - started) + if push_sec < on_air_deadline: + continue + group = yt_assign_db.get_group(gid) or {} + snap = _yn.studio_snapshot_for_group(group, max_age_sec=75.0) + try: + age = snap.get("age_sec") + fresh = age is not None and float(age) <= 75.0 + except (TypeError, ValueError): + fresh = bool(snap.get("received_at")) + on_air = bool(snap.get("on_air")) + live_status = str(snap.get("live_status") or "").strip().lower() + page_open = bool(snap.get("live_page_open")) + preparing = live_status == "preparing" or bool(snap.get("preparing_stream")) + pending = live_status in {"waiting", "ready", "signed_out", "offline", "preparing"} + if preparing: + pending = True + elif live_status in {"encoder_lost", "stalled", "live"}: + pending = False + prep_deadline = min(on_air_deadline, 45.0) + kill_prep = preparing and push_sec >= prep_deadline + if not (fresh and page_open and (not on_air) and (pending or kill_prep)): + continue + why = "Preparing stream(预览未就绪)" if preparing else (live_status or "待开播/NODATA") + err = ( + f"Studio 仍为 {why}(未 on_air),孤儿推流已 {int(push_sec)}s — 已自动停止" + ) + try: + os.kill(orphan_pid, signal.SIGTERM) + except Exception: + try: + os.kill(orphan_pid, signal.SIGKILL) + except Exception: + pass + boot = youtube_relay_db._parse_recent_log(st_row.get("recent_log")) + boot.append(f"[relay] {err}") + tripped, cool_msg = self._note_studio_not_on_air(gid) + if tripped: + err = cool_msg + boot.append(f"[relay] {cool_msg}") + youtube_relay_db.upsert_relay_state( + gid, + status="paused_studio" if tripped else "waiting", + ffmpeg_pid=0, + speed=0, + frame=0, + error=err, + recent_log=boot[-40:], + ) + await asyncio.to_thread( + relay_sessions.end_session, gid, reason="studio_not_on_air_orphan" + ) + self._manual_hold.discard(gid) + except Exception: + pass + youtube_relay_pipeline = YoutubeRelayPipeline() diff --git a/backend/app/youtube_relay_status.py b/backend/app/youtube_relay_status.py index 29280b3..a4cc810 100644 --- a/backend/app/youtube_relay_status.py +++ b/backend/app/youtube_relay_status.py @@ -208,6 +208,12 @@ def summarize_relay_group( elif raw_status == "error" and st.get("error") and not armed: business_status = "error" business_note = str(st.get("error") or "")[:240] + elif raw_status == "paused_exclusive": + business_status = "paused_exclusive" + business_note = str(st.get("error") or "单路独占:其他频道推流中").strip()[:240] + elif raw_status == "paused_studio": + business_status = "paused_studio" + business_note = str(st.get("error") or "Studio 未 on_air 熔断中").strip()[:240] elif raw_status == "reconnecting" and armed: business_status = "relay_starting" business_note = "推流中断,正在重连" @@ -286,6 +292,7 @@ def summarize_relay_group( "url_count": len(featured_urls), "douyin_count": douyin_count, "has_stream_key": has_key, + "stream_key": str(group.get("stream_key") or "").strip(), "stream_key_suffix": _key_suffix(group), "push_seconds": float(st.get("push_seconds") or 0) if is_pushing else 0.0, "started_at": float(st.get("started_at") or 0), diff --git a/backend/app/yt_assign_db.py b/backend/app/yt_assign_db.py index 6cb2386..753574e 100644 --- a/backend/app/yt_assign_db.py +++ b/backend/app/yt_assign_db.py @@ -107,6 +107,8 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: ("neko_open_prefer", "TEXT NOT NULL DEFAULT 'local'"), # Push category: normal (manual / featured) | time_slot (24/N schedule + live sources) ("category", "TEXT NOT NULL DEFAULT 'normal'"), + # time_slot only: off ⇒ same as missing stream key (excluded from 24/N) + ("time_slot_armed", "INTEGER NOT NULL DEFAULT 1"), ]: if col not in gcols: conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}") @@ -327,6 +329,31 @@ def group_is_time_slot(group: dict[str, Any] | None) -> bool: return normalize_assign_category(group.get("category")) == "time_slot" +def group_time_slot_armed(group: dict[str, Any] | None) -> bool: + """Whether a time_slot card participates in 24/N. Default True (legacy rows).""" + if group is None: + return False + if "time_slot_armed" not in group: + return True + v = group.get("time_slot_armed") + if v is None: + return True + if isinstance(v, str): + return v.strip().lower() not in {"0", "false", "no", "off", ""} + return bool(v) + + +def group_eligible_for_time_slot(group: dict[str, Any] | None) -> bool: + """时间段排班资格:分类=时间段 + 有 KEY + 右上角开关开。""" + if not group or not group.get("enabled"): + return False + if not group_is_time_slot(group): + return False + if not _group_has_stream_key(group): + return False + return group_time_slot_armed(group) + + def _public_group( row: dict[str, Any], *, @@ -340,6 +367,7 @@ def _public_group( out["neko_enabled"] = bool(out.get("neko_enabled")) out["category"] = normalize_assign_category(out.get("category")) out["category_label"] = ASSIGN_CATEGORY_LABELS.get(out["category"], "普通") + out["time_slot_armed"] = group_time_slot_armed(out) neko_id = int(out.get("neko_instance_id") or 0) out["neko_instance_id"] = neko_id sk = str(out.get("stream_key") or "") @@ -481,12 +509,13 @@ def _feat_select_sql() -> str: def list_groups( *, include_urls: bool = True, - include_secret: bool = False, + include_secret: bool = True, featured_only: bool = False, ) -> list[dict[str, Any]]: """List assign groups. featured_only=True: load featured URLs only (no pool/slots/enrich) — for relay status polls. + include_secret=True by default so ops UI can show/copy live stream keys. """ with _lock: conn = _connect() @@ -730,6 +759,7 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]: "sort_order", "neko_enabled", "category", + "time_slot_armed", } patch: dict[str, Any] = {} for k, v in fields.items(): @@ -739,6 +769,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]: patch[k] = 1 if v else 0 elif k == "neko_enabled": patch[k] = 1 if v else 0 + elif k == "time_slot_armed": + patch[k] = 1 if v else 0 elif k == "category": patch[k] = normalize_assign_category(v) elif k == "sort_order": @@ -1716,9 +1748,7 @@ def group_in_rotation_slot(group_id: str, *, keyed_only: bool | None = None) -> keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode")) except Exception: keyed_only = False - if keyed_only and not _group_has_stream_key(g): - return False - if keyed_only and not group_is_time_slot(g): + if keyed_only and not group_eligible_for_time_slot(g): return False ch_key = _group_yt_channel_key(g) sched = build_rotation_schedule(include_urls=False, keyed_only=keyed_only) @@ -1763,8 +1793,8 @@ def build_rotation_schedule( keyed_only = False enabled = [g for g in raw if g.get("enabled")] if keyed_only: - # 时间段排班:仅「时间段」分类 + 有 KEY 的频道参与 24/N - keyed = [g for g in enabled if _group_has_stream_key(g) and group_is_time_slot(g)] + # 时间段排班:时间段分类 + 有 KEY + 开关开(关=等同无 KEY) + keyed = [g for g in enabled if group_eligible_for_time_slot(g)] rotation_rows = _dedupe_groups_by_yt_channel(keyed) else: rotation_rows = [(g, []) for g in enabled] @@ -1836,6 +1866,36 @@ def build_rotation_schedule( } +def overlay_timeslot_test_schedule( + schedule: dict[str, Any] | None, + *, + test_on: bool, + test_group_id: str = "", +) -> dict[str, Any]: + """Mark forced test winner as active for UI; keep real clock in schedule_active.""" + out = dict(schedule or {}) + want = str(test_group_id or "").strip() + out["test_mode"] = bool(test_on) + out["test_group_id"] = want if test_on else "" + channels: list[dict[str, Any]] = [] + for raw in out.get("channels") or []: + if not isinstance(raw, dict): + continue + c = dict(raw) + c["schedule_active"] = bool(c.get("active")) + if test_on and want: + gid = str(c.get("group_id") or "") + aliases = [str(x) for x in (c.get("alias_group_ids") or []) if x] + forced = gid == want or want in aliases + c["active"] = forced + c["test_force"] = forced + else: + c["test_force"] = False + channels.append(c) + out["channels"] = channels + return out + + def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: bool = False, force: bool = False) -> dict[str, Any]: """Fill slot lists from Douyin live + 24h session stats; round-robin across groups.""" ranked = _rank_douyin_rooms_for_relay(limit=max(8, min(int(limit), 80))) diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index e0f5838..b8b2123 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -699,6 +699,11 @@ def list_yt_long_jobs(*, limit: int = 40, push_date: str = "") -> list[dict[str, def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]: + """Pending masters ready to record. + + Channel may be empty when YouTube upload slots were full at enqueue time + (cascade-only path). Those jobs must still be claimable for recording. + """ with _lock: conn = _connect() try: @@ -706,9 +711,12 @@ def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]: rows = conn.execute( """ SELECT j.* FROM yt_long_jobs j - INNER JOIN yt_long_channels c ON c.id = j.channel_pk + LEFT JOIN yt_long_channels c ON c.id = j.channel_pk AND j.channel_pk != '' WHERE j.status = 'pending' - AND c.enabled = 1 + AND ( + IFNULL(j.channel_pk, '') = '' + OR c.enabled = 1 + ) ORDER BY j.created_at ASC LIMIT ? """, @@ -760,15 +768,17 @@ def delete_yt_long_jobs_for_channel(channel_pk: str) -> dict[str, int]: conn.close() -def claim_due_yt_long_upload() -> dict[str, Any] | None: +def claim_due_yt_long_upload(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None: now = time.time() + skip = {str(x).strip().upper() for x in (skip_profile_ids or set()) if str(x).strip()} with _lock: conn = _connect() try: ensure_yt_long_tables(conn) - row = conn.execute( + rows = conn.execute( """ - SELECT j.* FROM yt_long_jobs j + SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id + FROM yt_long_jobs j INNER JOIN yt_long_channels c ON c.id = j.channel_pk WHERE j.status = 'scheduled' AND c.enabled = 1 @@ -776,13 +786,20 @@ def claim_due_yt_long_upload() -> dict[str, Any] | None: AND j.upload_at > 0 AND j.upload_at <= ? ORDER BY j.upload_at ASC, j.created_at ASC - LIMIT 1 + LIMIT 30 """, (now,), - ).fetchone() - if not row: + ).fetchall() + picked = None + for row in rows: + pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A" + if pid in skip: + continue + picked = row + break + if not picked: return None - jid = str(row["id"]) + jid = str(picked["id"]) cur = conn.execute( """ UPDATE yt_long_jobs @@ -802,6 +819,43 @@ def claim_due_yt_long_upload() -> dict[str, Any] | None: conn.close() +def defer_profile_yt_long_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int: + """Push due auto-uploads for this OAuth Client past cool-down.""" + pid = str(profile_id or "A").strip().upper() or "A" + until = float(until_ts or 0) + if until <= time.time(): + return 0 + now = time.time() + moved = 0 + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + rows = conn.execute( + """ + SELECT j.id FROM yt_long_jobs j + INNER JOIN yt_long_channels c ON c.id = j.channel_pk + WHERE j.status = 'scheduled' + AND j.clip_path != '' + AND j.upload_at > 0 + AND j.upload_at <= ? + AND UPPER(TRIM(COALESCE(NULLIF(c.oauth_profile_id, ''), 'A'))) = ? + """, + (now + 30, pid), + ).fetchall() + for row in rows: + conn.execute( + "UPDATE yt_long_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?", + (until + 15, (reason or "YouTube 接口配额冷静中,稍后自动重试")[:300], now, str(row["id"])), + ) + moved += 1 + if moved: + conn.commit() + finally: + conn.close() + return moved + + def count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int: day = push_date or "" with _lock: @@ -1260,7 +1314,9 @@ def channel_board(push_date: str = "") -> dict[str, Any]: (day, cid), ).fetchall() } - gap = max(0, dmax - used) if ch.get("enabled") else 0 + uploaded = int(by.get("uploaded") or 0) + # Progress / gap follow uploaded (Shorts parity); used keeps slot reservation. + gap = max(0, dmax - uploaded) if ch.get("enabled") else 0 total_gap += gap try: ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1) @@ -1302,7 +1358,7 @@ def channel_board(push_date: str = "") -> dict[str, Any]: "daily_max": dmax, "used": used, "gap": gap, - "uploaded": int(by.get("uploaded") or 0), + "uploaded": uploaded, "scheduled": int(by.get("scheduled") or 0) + int(by.get("uploading") or 0), "pending": int(by.get("pending") or 0) + int(by.get("recording") or 0), "failed": int(by.get("failed") or 0), diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index b2c8f55..c383318 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -655,8 +655,11 @@ class YtLongPipeline: if cfg.get("yt_long_auto_upload", True): max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) + from .shorts_yt_quota import blocked_profile_ids + + skip = blocked_profile_ids(cfg) while self._active_uploads < max_up: - job = yt_long_db.claim_due_yt_long_upload() + job = yt_long_db.claim_due_yt_long_upload(skip_profile_ids=skip or None) if not job: break self._active_uploads += 1 @@ -818,29 +821,61 @@ class YtLongPipeline: except Exception as exc: self.last_error = str(exc)[:240] msg = str(exc) - if "QUOTA_EXCEEDED" in msg or "quotaExceeded" in msg: + from .shorts_upload import is_upload_quota_error + + is_quota = ( + "QUOTA_EXCEEDED" in msg + or "quotaExceeded" in msg + or is_upload_quota_error(msg) + ) + if is_quota: + should_notify = True try: - from .shorts_yt_quota import pause_uploads_until_reset, profile_id_for_channel + from .shorts_yt_quota import mark_api_quota_cooldown, profile_id_for_channel ch = yt_long_db.get_yt_long_channel(str(job.get("channel_pk") or "")) pid = profile_id_for_channel(ch) if ch else "A" - pause_uploads_until_reset(profile_id=pid, reason=msg[:160]) + until, should_notify = mark_api_quota_cooldown( + profile_id=pid, reason=msg[:160] + ) + try: + yt_long_db.defer_profile_yt_long_uploads( + pid, + until, + reason=f"Client {pid} 接口配额冷静,稍后自动重试", + ) + except Exception: + pass yt_long_db.mark_yt_long_api_limited(reason=msg[:160]) yt_long_db.reconcile_yt_long_upload_caps() except Exception: - pass - yt_long_db.update_yt_long_job( - str(job.get("id") or ""), - status="failed", - error=str(exc)[:500], - finished_at=time.time(), - ) - _emit( - "yt_long_fail", - "error", - f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}", - job, - ) + should_notify = True + yt_long_db.update_yt_long_job( + str(job.get("id") or ""), + status="failed", + error=str(exc)[:500], + finished_at=time.time(), + ) + if should_notify: + _emit( + "yt_long_fail", + "warn", + f"长视频:YouTube 接口配额用尽(冷静后重试,不拦手动):{str(exc)[:80]}", + job, + ) + else: + yt_long_db.update_yt_long_job( + str(job.get("id") or ""), + status="failed", + error=str(exc)[:500], + finished_at=time.time(), + ) + _emit( + "yt_long_fail", + "error", + f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}", + job, + ) finally: self._active_uploads = max(0, self._active_uploads - 1) diff --git a/backend/app/yt_stream_key_db.py b/backend/app/yt_stream_key_db.py new file mode 100644 index 0000000..7f8df84 --- /dev/null +++ b/backend/app/yt_stream_key_db.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- +"""Standalone YouTube channel ↔ stream-key registry (archive / recovery). + +Isolated from yt_assign_groups relay path and Neko. Editing this table never +starts/stops Neko or mutates assign group stream_key unless an explicit +write-back API is called later. +""" +from __future__ import annotations + +import sqlite3 +import time +import uuid +from typing import Any, Optional + +from .db import _connect, _lock, _row_to_dict +from .yt_assign_db import _sanitize_stream_key + + +def ensure_stream_key_tables(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS yt_stream_key_registry ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + youtube_channel_id TEXT NOT NULL DEFAULT '', + channel_pk TEXT NOT NULL DEFAULT '', + assign_group_id TEXT NOT NULL DEFAULT '', + stream_key TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + sort_order INTEGER NOT NULL DEFAULT 0, + created_at REAL NOT NULL, + updated_at REAL NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_stream_key_ycid " + "ON yt_stream_key_registry(youtube_channel_id)" + ) + + +def _mask(sk: str) -> dict[str, Any]: + raw = str(sk or "") + return { + "has_stream_key": bool(raw.strip()), + "stream_key_masked": ("***" + raw[-4:]) if len(raw) > 6 else ("***" if raw else ""), + "stream_key_suffix": raw[-4:] if len(raw) >= 4 else raw, + } + + +def _public_row(row: dict[str, Any], *, include_secret: bool = False) -> dict[str, Any]: + out = dict(row) + sk = str(out.get("stream_key") or "") + out.update(_mask(sk)) + if include_secret: + out["stream_key"] = sk + else: + out.pop("stream_key", None) + return out + + +def list_entries(*, include_secret: bool = True) -> dict[str, Any]: + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + rows = conn.execute( + """ + SELECT * FROM yt_stream_key_registry + ORDER BY sort_order ASC, updated_at DESC, name ASC + """ + ).fetchall() + items = [_public_row(_row_to_dict(r), include_secret=include_secret) for r in rows] + return {"ok": True, "items": items, "total": len(items)} + finally: + conn.close() + + +def get_entry(entry_id: str, *, include_secret: bool = False) -> Optional[dict[str, Any]]: + eid = str(entry_id or "").strip() + if not eid: + return None + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + row = conn.execute( + "SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,) + ).fetchone() + if not row: + return None + return _public_row(_row_to_dict(row), include_secret=include_secret) + finally: + conn.close() + + +def upsert_entry( + *, + entry_id: str = "", + name: str = "", + youtube_channel_id: str = "", + channel_pk: str = "", + assign_group_id: str = "", + stream_key: str = "", + note: str = "", + sort_order: int | None = None, +) -> dict[str, Any]: + now = time.time() + eid = str(entry_id or "").strip() or str(uuid.uuid4()) + sk = _sanitize_stream_key(stream_key) + ycid = str(youtube_channel_id or "").strip() + name_s = str(name or "").strip() or ycid or "未命名" + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + existing = conn.execute( + "SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,) + ).fetchone() + if existing: + prev = _row_to_dict(existing) + # Keep previous key if caller sent empty (edit other fields only) + if not sk: + sk = str(prev.get("stream_key") or "") + so = int(prev.get("sort_order") or 0) if sort_order is None else int(sort_order) + conn.execute( + """ + UPDATE yt_stream_key_registry SET + name=?, youtube_channel_id=?, channel_pk=?, assign_group_id=?, + stream_key=?, note=?, sort_order=?, updated_at=? + WHERE id=? + """, + ( + name_s, + ycid, + str(channel_pk or "").strip(), + str(assign_group_id or "").strip(), + sk, + str(note or "").strip(), + so, + now, + eid, + ), + ) + else: + so = 0 if sort_order is None else int(sort_order) + conn.execute( + """ + INSERT INTO yt_stream_key_registry( + id, name, youtube_channel_id, channel_pk, assign_group_id, + stream_key, note, sort_order, created_at, updated_at + ) VALUES (?,?,?,?,?,?,?,?,?,?) + """, + ( + eid, + name_s, + ycid, + str(channel_pk or "").strip(), + str(assign_group_id or "").strip(), + sk, + str(note or "").strip(), + so, + now, + now, + ), + ) + conn.commit() + row = conn.execute( + "SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,) + ).fetchone() + return _public_row(_row_to_dict(row), include_secret=True) + finally: + conn.close() + + +def delete_entry(entry_id: str) -> bool: + eid = str(entry_id or "").strip() + if not eid: + return False + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + cur = conn.execute("DELETE FROM yt_stream_key_registry WHERE id=?", (eid,)) + conn.commit() + return cur.rowcount > 0 + finally: + conn.close() + + +def import_from_assign_groups(*, replace: bool = False) -> dict[str, Any]: + """Snapshot current assign-group keys into registry. Does not modify assign/Neko.""" + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + # assign tables must exist + try: + from .yt_assign_db import ensure_yt_assign_tables + + ensure_yt_assign_tables(conn) + except Exception: + pass + if replace: + conn.execute("DELETE FROM yt_stream_key_registry") + assign_rows = conn.execute( + """ + SELECT id, name, channel_pk, youtube_channel_id, stream_key, note, sort_order + FROM yt_assign_groups + ORDER BY sort_order ASC, name ASC + """ + ).fetchall() + inserted = 0 + updated = 0 + skipped = 0 + now = time.time() + for r in assign_rows: + d = _row_to_dict(r) + sk = _sanitize_stream_key(str(d.get("stream_key") or "")) + ycid = str(d.get("youtube_channel_id") or "").strip() + gid = str(d.get("id") or "").strip() + if not sk and not ycid: + skipped += 1 + continue + existing = None + if gid: + existing = conn.execute( + "SELECT id, stream_key FROM yt_stream_key_registry WHERE assign_group_id=?", + (gid,), + ).fetchone() + if existing is None and ycid: + existing = conn.execute( + "SELECT id, stream_key FROM yt_stream_key_registry WHERE youtube_channel_id=? LIMIT 1", + (ycid,), + ).fetchone() + name_s = str(d.get("name") or "").strip() or ycid or "未命名" + if existing: + ed = _row_to_dict(existing) + eid = str(ed["id"]) + conn.execute( + """ + UPDATE yt_stream_key_registry SET + name=?, youtube_channel_id=?, channel_pk=?, assign_group_id=?, + stream_key=?, note=?, sort_order=?, updated_at=? + WHERE id=? + """, + ( + name_s, + ycid, + str(d.get("channel_pk") or "").strip(), + gid, + sk or str(ed.get("stream_key") or ""), + str(d.get("note") or "").strip(), + int(d.get("sort_order") or 0), + now, + eid, + ), + ) + updated += 1 + else: + conn.execute( + """ + INSERT INTO yt_stream_key_registry( + id, name, youtube_channel_id, channel_pk, assign_group_id, + stream_key, note, sort_order, created_at, updated_at + ) VALUES (?,?,?,?,?,?,?,?,?,?) + """, + ( + str(uuid.uuid4()), + name_s, + ycid, + str(d.get("channel_pk") or "").strip(), + gid, + sk, + str(d.get("note") or "").strip(), + int(d.get("sort_order") or 0), + now, + now, + ), + ) + inserted += 1 + conn.commit() + total = conn.execute("SELECT COUNT(*) FROM yt_stream_key_registry").fetchone()[0] + return { + "ok": True, + "inserted": inserted, + "updated": updated, + "skipped": skipped, + "total": int(total), + } + finally: + conn.close() + + +def export_all() -> dict[str, Any]: + return list_entries(include_secret=True) + + +def import_payload(items: list[dict[str, Any]], *, replace: bool = False) -> dict[str, Any]: + """Merge/replace registry from peer export. Never touches assign/Neko.""" + if not isinstance(items, list): + raise ValueError("items must be a list") + with _lock: + conn = _connect() + try: + ensure_stream_key_tables(conn) + if replace: + conn.execute("DELETE FROM yt_stream_key_registry") + now = time.time() + n = 0 + for it in items: + if not isinstance(it, dict): + continue + eid = str(it.get("id") or "").strip() or str(uuid.uuid4()) + sk = _sanitize_stream_key(str(it.get("stream_key") or "")) + ycid = str(it.get("youtube_channel_id") or "").strip() + name_s = str(it.get("name") or "").strip() or ycid or "未命名" + conn.execute( + "DELETE FROM yt_stream_key_registry WHERE id=?", (eid,) + ) + conn.execute( + """ + INSERT INTO yt_stream_key_registry( + id, name, youtube_channel_id, channel_pk, assign_group_id, + stream_key, note, sort_order, created_at, updated_at + ) VALUES (?,?,?,?,?,?,?,?,?,?) + """, + ( + eid, + name_s, + ycid, + str(it.get("channel_pk") or "").strip(), + str(it.get("assign_group_id") or "").strip(), + sk, + str(it.get("note") or "").strip(), + int(it.get("sort_order") or 0), + float(it.get("created_at") or now), + now, + ), + ) + n += 1 + conn.commit() + total = conn.execute("SELECT COUNT(*) FROM yt_stream_key_registry").fetchone()[0] + return {"ok": True, "imported": n, "total": int(total)} + finally: + conn.close() diff --git a/backend/app/yt_studio_db.py b/backend/app/yt_studio_db.py index 9e613f0..e3aa9ef 100644 --- a/backend/app/yt_studio_db.py +++ b/backend/app/yt_studio_db.py @@ -198,7 +198,7 @@ def list_samples( limit: int = 200, ) -> list[dict[str, Any]]: _ensure() - lim = max(1, min(2000, int(limit))) + lim = max(1, min(5000, int(limit))) clauses: list[str] = [] args: list[Any] = [] if group_id: @@ -247,3 +247,1145 @@ def session_stats_for_group(group_id: str, *, since_ts: float = 0) -> dict[str, "total_views": totals[0] if totals else None, "neko_kinds": sorted({str(r.get("neko_kind") or "") for r in rows if r.get("neko_kind")}), } + + +def _sample_viewer(row: dict[str, Any]) -> int | None: + v = row.get("viewer_count") + if v is None or v == "": + return None + try: + return max(0, int(v)) + except (TypeError, ValueError): + return None + + +def _sample_total_views(row: dict[str, Any]) -> int | None: + v = row.get("total_views") + if v is None or v == "": + return None + try: + return max(0, int(v)) + except (TypeError, ValueError): + return None + + +def cluster_live_sessions( + samples: list[dict[str, Any]], + *, + gap_sec: float = 1500.0, +) -> list[dict[str, Any]]: + """Split Studio samples into live sessions (gap / uuid / on_air edges).""" + rows = sorted( + (r for r in samples if float(r.get("ts") or 0) > 0), + key=lambda r: float(r["ts"]), + ) + if not rows: + return [] + + sessions: list[list[dict[str, Any]]] = [] + cur: list[dict[str, Any]] = [] + last_ts = 0.0 + last_uuid = "" + last_on_air = False + + for r in rows: + ts = float(r.get("ts") or 0) + uuid = str(r.get("relay_session_uuid") or "").strip() + on_air = bool(r.get("on_air")) + meaningful = ( + on_air + or _sample_viewer(r) is not None + or _sample_total_views(r) is not None + or str(r.get("live_duration") or "").strip() + ) + if not meaningful and not cur: + continue + + new_sess = False + if not cur: + new_sess = True + elif uuid and last_uuid and uuid != last_uuid: + new_sess = True + elif last_ts and (ts - last_ts) > gap_sec: + new_sess = True + elif on_air and not last_on_air and last_ts and (ts - last_ts) > 180: + new_sess = True + + if new_sess and cur: + sessions.append(cur) + cur = [] + if meaningful or cur: + cur.append(r) + last_ts = ts + if uuid: + last_uuid = uuid + last_on_air = on_air + + if cur: + sessions.append(cur) + + out: list[dict[str, Any]] = [] + for idx, chunk in enumerate(sessions): + viewers = [v for v in (_sample_viewer(r) for r in chunk) if v is not None] + totals = [v for v in (_sample_total_views(r) for r in chunk) if v is not None] + likes = [] + for r in chunk: + try: + if r.get("like_count") is not None: + likes.append(int(r["like_count"])) + except (TypeError, ValueError): + pass + started = float(chunk[0]["ts"]) + ended = float(chunk[-1]["ts"]) + dur_sec = max(0.0, ended - started) + # Prefer Studio live_duration_sec if larger (ingest lag) + for r in reversed(chunk): + try: + ld = float(r.get("live_duration_sec") or 0) + if ld > dur_sec: + dur_sec = ld + break + except (TypeError, ValueError): + pass + rooms = [] + anchors = [] + titles = [] + neko_kinds_list = [] + uuids = [] + healths = [] + statuses = [] + for r in chunk: + rid = str(r.get("source_room_id") or "").strip() + if rid and rid not in rooms: + rooms.append(rid) + an = str(r.get("anchor_name") or "").strip() + if an and an not in anchors: + anchors.append(an) + ti = str(r.get("stream_title") or "").strip() + if ti and ti not in titles: + titles.append(ti) + nk = str(r.get("neko_kind") or "").strip() + if nk and nk not in neko_kinds_list: + neko_kinds_list.append(nk) + uid = str(r.get("relay_session_uuid") or "").strip() + if uid and uid not in uuids: + uuids.append(uid) + h = str(r.get("health") or "").strip() + if h and h not in healths: + healths.append(h) + st = str(r.get("live_status") or "").strip() + if st and st not in statuses: + statuses.append(st) + + minute_reports = [] + by_min: dict[int, dict[str, Any]] = {} + for r in chunk: + ts = float(r["ts"]) + by_min[int(ts // 60)] = { + "ts": ts, + "on_air": bool(r.get("on_air")), + "live_status": str(r.get("live_status") or ""), + "health": str(r.get("health") or ""), + "viewer_count": _sample_viewer(r), + "total_views": _sample_total_views(r), + "live_duration": str(r.get("live_duration") or ""), + "live_duration_sec": r.get("live_duration_sec"), + "source_room_id": str(r.get("source_room_id") or ""), + "anchor_name": str(r.get("anchor_name") or ""), + "neko_kind": str(r.get("neko_kind") or ""), + } + minute_reports = [by_min[k] for k in sorted(by_min)] + + from .timeutil import push_date_from_ts + + out.append( + { + "id": f"studio-{idx}-{int(started)}", + "started_at": started, + "ended_at": ended, + "push_date": push_date_from_ts(started), + "duration_sec": round(dur_sec, 1), + "sample_count": len(chunk), + "minute_count": len(minute_reports), + "peak_viewers": max(viewers) if viewers else None, + "avg_viewers": round(sum(viewers) / len(viewers), 1) if viewers else None, + "end_viewers": viewers[-1] if viewers else None, + "start_viewers": viewers[0] if viewers else None, + "max_total_views": max(totals) if totals else None, + "start_total_views": totals[0] if totals else None, + "end_total_views": totals[-1] if totals else None, + "max_likes": max(likes) if likes else None, + "live_duration": str(chunk[-1].get("live_duration") or ""), + "on_air_ratio": round( + sum(1 for r in chunk if r.get("on_air")) / max(1, len(chunk)), 3 + ), + "source_rooms": rooms, + "anchors": anchors, + "stream_titles": titles[:8], + "neko_kinds": neko_kinds_list, + "relay_session_uuids": uuids, + "healths": healths, + "live_statuses": statuses, + "source_url": str(chunk[-1].get("source_url") or chunk[0].get("source_url") or ""), + "studio_url": str(chunk[-1].get("studio_url") or ""), + "detect_sources": sorted( + { + str(r.get("detect_source") or "") + for r in chunk + if str(r.get("detect_source") or "").strip() + } + ), + "minute_reports": minute_reports, + } + ) + out.sort(key=lambda s: float(s.get("started_at") or 0), reverse=True) + return out + + +def daily_rollup_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: + by_day: dict[str, dict[str, Any]] = {} + for s in sessions: + day = str(s.get("push_date") or "") + if not day: + continue + bucket = by_day.setdefault( + day, + { + "date": day, + "session_count": 0, + "live_sec": 0.0, + "sample_count": 0, + "peak_viewers": None, + "avg_viewers_sum": 0.0, + "avg_viewers_n": 0, + "max_total_views": None, + "rooms": set(), + "anchors": set(), + }, + ) + bucket["session_count"] += 1 + bucket["live_sec"] += float(s.get("duration_sec") or 0) + bucket["sample_count"] += int(s.get("sample_count") or 0) + pk = s.get("peak_viewers") + if pk is not None: + cur = bucket["peak_viewers"] + bucket["peak_viewers"] = int(pk) if cur is None else max(int(cur), int(pk)) + av = s.get("avg_viewers") + if av is not None: + bucket["avg_viewers_sum"] += float(av) + bucket["avg_viewers_n"] += 1 + tv = s.get("max_total_views") + if tv is not None: + cur = bucket["max_total_views"] + bucket["max_total_views"] = int(tv) if cur is None else max(int(cur), int(tv)) + for rid in s.get("source_rooms") or []: + bucket["rooms"].add(str(rid)) + for an in s.get("anchors") or []: + bucket["anchors"].add(str(an)) + + rows = [] + for day in sorted(by_day.keys(), reverse=True): + b = by_day[day] + n = int(b["avg_viewers_n"] or 0) + rows.append( + { + "date": day, + "session_count": b["session_count"], + "live_sec": round(float(b["live_sec"]), 1), + "live_hours": round(float(b["live_sec"]) / 3600.0, 2), + "sample_count": b["sample_count"], + "peak_viewers": b["peak_viewers"], + "avg_viewers": round(b["avg_viewers_sum"] / n, 1) if n else None, + "max_total_views": b["max_total_views"], + "room_count": len(b["rooms"]), + "rooms": sorted(b["rooms"]), + "anchors": sorted(b["anchors"]), + } + ) + return rows + + +def hour_heatmap_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Beijing-hour buckets: live minutes + peak concurrent.""" + from .timeutil import beijing_from_ts + + hours = [ + {"hour": h, "live_sec": 0.0, "sample_count": 0, "peak_viewers": None, "session_touches": 0} + for h in range(24) + ] + for s in sessions: + reports = s.get("minute_reports") or [] + touched = set() + for r in reports: + ts = float(r.get("ts") or 0) + if ts <= 0: + continue + h = int(beijing_from_ts(ts).hour) + hours[h]["live_sec"] += 60.0 + hours[h]["sample_count"] += 1 + touched.add(h) + v = r.get("viewer_count") + if v is not None: + cur = hours[h]["peak_viewers"] + hours[h]["peak_viewers"] = int(v) if cur is None else max(int(cur), int(v)) + for h in touched: + hours[h]["session_touches"] += 1 + for h in hours: + h["live_sec"] = round(float(h["live_sec"]), 1) + h["live_minutes"] = round(float(h["live_sec"]) / 60.0, 1) + return hours + + +def room_affinity_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: + by_room: dict[str, dict[str, Any]] = {} + for s in sessions: + rooms = s.get("source_rooms") or [] + if not rooms: + rooms = [""] + for rid in rooms: + key = str(rid or "").strip() or "(unknown)" + b = by_room.setdefault( + key, + { + "room_id": key if key != "(unknown)" else "", + "session_count": 0, + "live_sec": 0.0, + "peak_viewers": None, + "max_total_views": None, + "anchors": set(), + "last_started_at": 0.0, + }, + ) + b["session_count"] += 1 + b["live_sec"] += float(s.get("duration_sec") or 0) + pk = s.get("peak_viewers") + if pk is not None: + cur = b["peak_viewers"] + b["peak_viewers"] = int(pk) if cur is None else max(int(cur), int(pk)) + tv = s.get("max_total_views") + if tv is not None: + cur = b["max_total_views"] + b["max_total_views"] = int(tv) if cur is None else max(int(cur), int(tv)) + for an in s.get("anchors") or []: + b["anchors"].add(str(an)) + b["last_started_at"] = max(float(b["last_started_at"] or 0), float(s.get("started_at") or 0)) + rows = [] + for b in by_room.values(): + rows.append( + { + "room_id": b["room_id"], + "session_count": b["session_count"], + "live_sec": round(float(b["live_sec"]), 1), + "live_hours": round(float(b["live_sec"]) / 3600.0, 2), + "peak_viewers": b["peak_viewers"], + "max_total_views": b["max_total_views"], + "anchors": sorted(b["anchors"]), + "last_started_at": b["last_started_at"] or None, + "douyin_url": ( + f"https://live.douyin.com/{b['room_id']}" if b["room_id"] else "" + ), + } + ) + rows.sort(key=lambda r: (float(r.get("live_sec") or 0), int(r.get("session_count") or 0)), reverse=True) + return rows + + +def resolve_douyin_room_media(room_id: str) -> dict[str, Any]: + """Nickname + cover + URL for a Douyin room (rooms / sessions / pool).""" + from .db import _connect, _lock + + rid = str(room_id or "").strip() + out = { + "room_id": rid, + "anchor_name": "", + "cover_url": "", + "avatar_url": "", + "douyin_url": f"https://live.douyin.com/{rid}" if rid else "", + "session_cover_url": "", + "note": "", + } + if not rid: + return out + with _lock: + conn = _connect() + try: + room = conn.execute( + "SELECT last_anchor, note, avatar_url, url FROM rooms WHERE room_id = ? LIMIT 1", + (rid,), + ).fetchone() + if room: + out["anchor_name"] = str(room["last_anchor"] or "").strip() + out["note"] = str(room["note"] or "").strip() + av = str(room["avatar_url"] or "").strip() + out["avatar_url"] = av + if av.startswith("http") or av.startswith("/"): + out["cover_url"] = av + ru = str(room["url"] or "").strip() + if ru: + out["douyin_url"] = ru + sess = conn.execute( + """ + SELECT id, cover_path, anchor_name FROM sessions + WHERE room_id = ? + ORDER BY started_at DESC LIMIT 1 + """, + (rid,), + ).fetchone() + if sess: + sid = str(sess["id"] or "") + if sid: + out["session_cover_url"] = f"/api/sessions/{sid}/cover" + if not out["cover_url"]: + out["cover_url"] = out["session_cover_url"] + if not out["anchor_name"]: + out["anchor_name"] = str(sess["anchor_name"] or "").strip() + pool = conn.execute( + """ + SELECT title, cover_url, url, note FROM yt_assign_pool_urls + WHERE room_id = ? OR url LIKE ? + ORDER BY updated_at DESC LIMIT 1 + """, + (rid, f"%{rid}%"), + ).fetchone() + if pool: + if not out["anchor_name"]: + out["anchor_name"] = str(pool["title"] or pool["note"] or "").strip() + cu = str(pool["cover_url"] or "").strip() + if cu and (cu.startswith("http") or cu.startswith("/")) and not out["cover_url"]: + out["cover_url"] = cu + if str(pool["url"] or "").strip(): + out["douyin_url"] = str(pool["url"]).strip() + except Exception: + pass + finally: + conn.close() + if not out["cover_url"] and out["session_cover_url"]: + out["cover_url"] = out["session_cover_url"] + return out + + +def _perf_score( + *, + avg_viewers: float | None, + peak_viewers: float | None, + max_total_views: float | None, + live_hours: float, + session_count: int, +) -> float: + """Rank score for arranging YouTube live from a Douyin source.""" + avg = float(avg_viewers or 0) + peak = float(peak_viewers or 0) + tot = float(max_total_views or 0) + hours = float(live_hours or 0) + n = max(1, int(session_count or 0)) + # Reliability weight: more sessions → trust avg more + rel = min(1.5, 0.6 + 0.15 * n) + return round(avg * 1.2 * rel + peak * 0.35 + (tot / 500.0) + hours * 4.0, 2) + + +def source_performance_from_sessions( + sessions: list[dict[str, Any]], + *, + group_id: str = "", + channel_name: str = "", + youtube_channel_id: str = "", +) -> list[dict[str, Any]]: + """Per Douyin room performance on one YouTube channel (for planning).""" + from .timeutil import beijing_from_ts + + by_room: dict[str, dict[str, Any]] = {} + for s in sessions: + rooms = [str(x).strip() for x in (s.get("source_rooms") or []) if str(x).strip()] + if not rooms: + continue + reports = s.get("minute_reports") or [] + for rid in rooms: + b = by_room.setdefault( + rid, + { + "room_id": rid, + "session_count": 0, + "live_sec": 0.0, + "peaks": [], + "avgs": [], + "totals": [], + "anchors": set(), + "titles": set(), + "last_started_at": 0.0, + "hour_live_sec": [0.0] * 24, + "hour_peak": [None] * 24, + "hour_samples": [0] * 24, + "weekday_live_sec": [0.0] * 7, + "weekday_peak": [None] * 7, + "session_ids": [], + }, + ) + b["session_count"] += 1 + b["live_sec"] += float(s.get("duration_sec") or 0) + if s.get("peak_viewers") is not None: + b["peaks"].append(float(s["peak_viewers"])) + if s.get("avg_viewers") is not None: + b["avgs"].append(float(s["avg_viewers"])) + if s.get("max_total_views") is not None: + b["totals"].append(float(s["max_total_views"])) + for an in s.get("anchors") or []: + if an: + b["anchors"].add(str(an)) + for ti in s.get("stream_titles") or []: + if ti: + b["titles"].add(str(ti)[:80]) + b["last_started_at"] = max(float(b["last_started_at"] or 0), float(s.get("started_at") or 0)) + b["session_ids"].append(s.get("id")) + # hour / weekday from minute reports (prefer), else session start + touched_h = set() + for r in reports: + ts = float(r.get("ts") or 0) + if ts <= 0: + continue + dt = beijing_from_ts(ts) + h = int(dt.hour) + wd = int(dt.weekday()) + b["hour_live_sec"][h] += 60.0 + b["hour_samples"][h] += 1 + touched_h.add(h) + v = r.get("viewer_count") + if v is not None: + try: + iv = int(v) + cur = b["hour_peak"][h] + b["hour_peak"][h] = iv if cur is None else max(int(cur), iv) + curw = b["weekday_peak"][wd] + b["weekday_peak"][wd] = iv if curw is None else max(int(curw), iv) + except (TypeError, ValueError): + pass + b["weekday_live_sec"][wd] += 60.0 + if not reports and s.get("started_at"): + dt = beijing_from_ts(float(s["started_at"])) + h = int(dt.hour) + wd = int(dt.weekday()) + dur = float(s.get("duration_sec") or 0) + b["hour_live_sec"][h] += dur + b["weekday_live_sec"][wd] += dur + if s.get("peak_viewers") is not None: + iv = int(s["peak_viewers"]) + cur = b["hour_peak"][h] + b["hour_peak"][h] = iv if cur is None else max(int(cur), iv) + + wd_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] + rows: list[dict[str, Any]] = [] + for rid, b in by_room.items(): + media = resolve_douyin_room_media(rid) + avg = round(sum(b["avgs"]) / len(b["avgs"]), 1) if b["avgs"] else None + peak = int(max(b["peaks"])) if b["peaks"] else None + tot = int(max(b["totals"])) if b["totals"] else None + live_h = round(float(b["live_sec"]) / 3600.0, 2) + score = _perf_score( + avg_viewers=avg, + peak_viewers=peak, + max_total_views=tot, + live_hours=live_h, + session_count=int(b["session_count"]), + ) + # best hours: by peak then live minutes + hour_rank = sorted( + range(24), + key=lambda h: ( + int(b["hour_peak"][h] or 0), + float(b["hour_live_sec"][h]), + ), + reverse=True, + ) + best_hours = [] + for h in hour_rank: + if not b["hour_live_sec"][h] and not b["hour_peak"][h]: + continue + best_hours.append( + { + "hour": h, + "label": f"{h:02d}:00–{(h + 1) % 24:02d}:00", + "peak_viewers": b["hour_peak"][h], + "live_minutes": round(float(b["hour_live_sec"][h]) / 60.0, 1), + "samples": b["hour_samples"][h], + } + ) + if len(best_hours) >= 5: + break + wd_rank = sorted( + range(7), + key=lambda w: (int(b["weekday_peak"][w] or 0), float(b["weekday_live_sec"][w])), + reverse=True, + ) + best_weekdays = [] + for w in wd_rank: + if not b["weekday_live_sec"][w] and not b["weekday_peak"][w]: + continue + best_weekdays.append( + { + "weekday": w, + "label": wd_names[w], + "peak_viewers": b["weekday_peak"][w], + "live_hours": round(float(b["weekday_live_sec"][w]) / 3600.0, 2), + } + ) + if len(best_weekdays) >= 3: + break + + anchor = media.get("anchor_name") or (sorted(b["anchors"])[0] if b["anchors"] else "") + tip = "" + if best_hours and avg is not None: + tip = ( + f"建议优先用该源:均值同时约 {avg}," + f"北京 {best_hours[0]['label']} 表现最好" + + (f"(峰 {best_hours[0]['peak_viewers']})" if best_hours[0].get("peak_viewers") is not None else "") + ) + elif avg is not None: + tip = f"有采样:均值同时 {avg},峰 {peak if peak is not None else '—'}" + else: + tip = "已关联过本频道,但 Studio 观看样本不足" + + rows.append( + { + "room_id": rid, + "anchor_name": anchor, + "cover_url": media.get("cover_url") or "", + "avatar_url": media.get("avatar_url") or "", + "douyin_url": media.get("douyin_url") or f"https://live.douyin.com/{rid}", + "group_id": group_id, + "channel_name": channel_name, + "youtube_channel_id": youtube_channel_id, + "session_count": int(b["session_count"]), + "live_sec": round(float(b["live_sec"]), 1), + "live_hours": live_h, + "peak_viewers": peak, + "avg_viewers": avg, + "max_total_views": tot, + "score": score, + "best_hours": best_hours, + "best_weekdays": best_weekdays, + "hour_heatmap": [ + { + "hour": h, + "live_minutes": round(float(b["hour_live_sec"][h]) / 60.0, 1), + "peak_viewers": b["hour_peak"][h], + } + for h in range(24) + ], + "stream_titles": sorted(b["titles"])[:6], + "last_started_at": b["last_started_at"] or None, + "planning_tip": tip, + "in_pool": False, + "in_featured": False, + "measured": True, + } + ) + rows.sort(key=lambda r: (float(r.get("score") or 0), float(r.get("avg_viewers") or 0)), reverse=True) + for i, r in enumerate(rows): + r["rank"] = i + 1 + return rows + + +def merge_pool_sources_into_rankings( + rankings: list[dict[str, Any]], + group: dict[str, Any], +) -> list[dict[str, Any]]: + """Append assigned pool/featured rooms that have no Studio samples yet.""" + by_id = {str(r.get("room_id") or ""): r for r in rankings if r.get("room_id")} + feat_ids = set() + pool_ids = set() + for u in group.get("featured") or []: + rid = str(u.get("room_id") or "").strip() + if rid: + feat_ids.add(rid) + for u in group.get("pool") or []: + rid = str(u.get("room_id") or "").strip() + if rid: + pool_ids.add(rid) + for r in rankings: + rid = str(r.get("room_id") or "") + r["in_featured"] = rid in feat_ids + r["in_pool"] = rid in pool_ids or rid in feat_ids + + extras = [] + for u in list(group.get("featured") or []) + list(group.get("pool") or []): + rid = str(u.get("room_id") or "").strip() + if not rid or rid in by_id: + if rid in by_id: + # enrich cover from pool if missing + if not by_id[rid].get("cover_url") and u.get("cover_url"): + by_id[rid]["cover_url"] = str(u.get("cover_url") or "") + if not by_id[rid].get("anchor_name"): + by_id[rid]["anchor_name"] = str(u.get("title") or u.get("anchor_name") or u.get("note") or "") + continue + media = resolve_douyin_room_media(rid) + cover = str(u.get("cover_url") or media.get("cover_url") or "") + anchor = str(u.get("title") or u.get("anchor_name") or media.get("anchor_name") or u.get("note") or "") + extras.append( + { + "room_id": rid, + "anchor_name": anchor, + "cover_url": cover, + "avatar_url": media.get("avatar_url") or "", + "douyin_url": str(u.get("url") or media.get("douyin_url") or f"https://live.douyin.com/{rid}"), + "group_id": str(group.get("id") or ""), + "channel_name": str(group.get("name") or ""), + "youtube_channel_id": str(group.get("youtube_channel_id") or ""), + "session_count": 0, + "live_sec": 0.0, + "live_hours": 0.0, + "peak_viewers": None, + "avg_viewers": None, + "max_total_views": None, + "score": 0.0, + "best_hours": [], + "best_weekdays": [], + "hour_heatmap": [{"hour": h, "live_minutes": 0, "peak_viewers": None} for h in range(24)], + "stream_titles": [], + "last_started_at": None, + "planning_tip": "在本频道池/精选中,但窗口内尚无 Studio 观看样本 — 开播后才会出排名", + "in_pool": True, + "in_featured": rid in feat_ids, + "measured": False, + "rank": None, + } + ) + by_id[rid] = extras[-1] + return rankings + extras + + +def build_fleet_source_matrix(*, days: int = 30, sample_limit: int = 5000) -> dict[str, Any]: + """Cross-channel: which Douyin room performs best on which YouTube channel.""" + from . import yt_assign_db + from .timeutil import push_date_from_ts + + days_n = max(1, min(90, int(days or 30))) + since = time.time() - days_n * 86400 + groups = yt_assign_db.list_groups(include_urls=False) + + all_pairs: list[dict[str, Any]] = [] + per_group_rankings: dict[str, list[dict[str, Any]]] = {} + for g in groups: + gid = str(g.get("id") or "") + if not gid: + continue + try: + an = build_group_analytics(gid, days=days_n, sample_limit=min(2500, int(sample_limit))) + except Exception: + continue + if not an.get("ok"): + continue + ranks = [r for r in (an.get("source_rankings") or []) if r.get("measured")] + per_group_rankings[gid] = ranks[:8] + all_pairs.extend(ranks) + + # Room-centric: for each room, best channel + all channel rows + by_room: dict[str, dict[str, Any]] = {} + for r in all_pairs: + rid = str(r.get("room_id") or "") + if not rid: + continue + bucket = by_room.setdefault( + rid, + { + "room_id": rid, + "anchor_name": r.get("anchor_name") or "", + "cover_url": r.get("cover_url") or "", + "douyin_url": r.get("douyin_url") or "", + "channels": [], + }, + ) + if not bucket["anchor_name"] and r.get("anchor_name"): + bucket["anchor_name"] = r["anchor_name"] + if not bucket["cover_url"] and r.get("cover_url"): + bucket["cover_url"] = r["cover_url"] + bucket["channels"].append( + { + "group_id": r.get("group_id"), + "channel_name": r.get("channel_name"), + "youtube_channel_id": r.get("youtube_channel_id"), + "score": r.get("score"), + "avg_viewers": r.get("avg_viewers"), + "peak_viewers": r.get("peak_viewers"), + "max_total_views": r.get("max_total_views"), + "live_hours": r.get("live_hours"), + "session_count": r.get("session_count"), + "best_hours": (r.get("best_hours") or [])[:3], + "best_weekdays": (r.get("best_weekdays") or [])[:2], + "planning_tip": r.get("planning_tip"), + } + ) + room_rows = [] + for rid, b in by_room.items(): + chans = sorted(b["channels"], key=lambda x: float(x.get("score") or 0), reverse=True) + best = chans[0] if chans else None + room_rows.append( + { + **b, + "channels": chans, + "best_channel": best, + "channel_count": len(chans), + "best_score": float(best["score"]) if best else 0, + } + ) + room_rows.sort(key=lambda x: float(x.get("best_score") or 0), reverse=True) + + # Recommendations: top pairings + pairings = sorted(all_pairs, key=lambda x: float(x.get("score") or 0), reverse=True)[:40] + + return { + "ok": True, + "window": { + "days": days_n, + "since_ts": since, + "generated_at": time.time(), + "today": push_date_from_ts(time.time()), + "group_count": len(groups), + "pair_count": len(all_pairs), + "room_count": len(room_rows), + }, + "recommendations": [ + { + "rank": i + 1, + "room_id": p.get("room_id"), + "anchor_name": p.get("anchor_name"), + "cover_url": p.get("cover_url"), + "douyin_url": p.get("douyin_url"), + "group_id": p.get("group_id"), + "channel_name": p.get("channel_name"), + "youtube_channel_id": p.get("youtube_channel_id"), + "score": p.get("score"), + "avg_viewers": p.get("avg_viewers"), + "peak_viewers": p.get("peak_viewers"), + "max_total_views": p.get("max_total_views"), + "live_hours": p.get("live_hours"), + "best_hours": (p.get("best_hours") or [])[:3], + "planning_tip": p.get("planning_tip"), + } + for i, p in enumerate(pairings) + ], + "rooms": room_rows[:80], + "groups": [ + { + "id": str(g.get("id") or ""), + "name": g.get("name"), + "youtube_channel_id": g.get("youtube_channel_id"), + "top_sources": per_group_rankings.get(str(g.get("id") or "")) or [], + } + for g in groups + ], + } + + +def build_group_analytics( + group_id: str, + *, + days: int = 30, + sample_limit: int = 4000, +) -> dict[str, Any]: + """Full channel live analytics payload for assign group detail page.""" + from . import yt_assign_db + from . import youtube_relay_sessions as relay_sessions + from .timeutil import push_date_from_ts + + gid = str(group_id or "").strip() + if not gid: + return {"ok": False, "error": "missing group_id"} + + g = yt_assign_db.get_group(gid) + if not g: + return {"ok": False, "error": "group_not_found"} + + days_n = max(1, min(90, int(days or 30))) + since = time.time() - days_n * 86400 + samples = list_samples(group_id=gid, since_ts=since, limit=max(200, min(5000, int(sample_limit)))) + # also try youtube_channel_id if group_id samples sparse + ycid = str(g.get("youtube_channel_id") or "").strip() + if ycid and len(samples) < 20: + extra = list_samples(youtube_channel_id=ycid, since_ts=since, limit=max(200, min(5000, int(sample_limit)))) + seen = {int(r.get("id") or 0) for r in samples} + for r in extra: + rid = int(r.get("id") or 0) + if rid and rid not in seen: + samples.append(r) + seen.add(rid) + + studio_sessions = cluster_live_sessions(samples) + daily = daily_rollup_from_sessions(studio_sessions) + hours = hour_heatmap_from_sessions(studio_sessions) + rooms = room_affinity_from_sessions(studio_sessions) + + relay = relay_sessions.list_sessions(group_id=gid, limit=200, offset=0) + relay_rows = relay.get("sessions") or [] + relay_stats = relay_sessions.summarize_sessions(group_id=gid, top_anchors=30) + + # Attach nearest relay push rows onto studio sessions + backfill Douyin room ids + for s in studio_sessions: + st = float(s.get("started_at") or 0) + en = float(s.get("ended_at") or 0) + matched = [] + for rs in relay_rows: + rs_st = float(rs.get("started_at") or 0) + rs_en = float(rs.get("ended_at") or rs_st) + if rs_st <= 0: + continue + # overlap + if rs_st <= en + 600 and rs_en >= st - 600: + matched.append( + { + "id": rs.get("id"), + "session_uuid": rs.get("session_uuid"), + "started_at": rs.get("started_at"), + "ended_at": rs.get("ended_at"), + "duration_seconds": rs.get("duration_seconds"), + "status": rs.get("status"), + "end_reason": rs.get("end_reason"), + "source_room_id": rs.get("source_room_id"), + "source_url": rs.get("source_url"), + "anchor_name": rs.get("anchor_name"), + "stream_title": rs.get("stream_title"), + } + ) + s["relay_pushes"] = matched[:8] + # Studio samples often omit room_id — borrow from overlapping FFmpeg pushes + existing = {str(x).strip() for x in (s.get("source_rooms") or []) if str(x).strip()} + anchors = {str(x).strip() for x in (s.get("anchors") or []) if str(x).strip()} + for rp in matched: + rid = str(rp.get("source_room_id") or "").strip() + if rid: + existing.add(rid) + an = str(rp.get("anchor_name") or "").strip() + if an: + anchors.add(an) + if not s.get("source_url") and rp.get("source_url"): + s["source_url"] = rp.get("source_url") + # Fallback: same Beijing day relay for this group (when Studio has viewers but no room) + if not existing: + day = str(s.get("push_date") or "") + day_relays = [ + rs + for rs in relay_rows + if str(rs.get("push_date") or "") == day and str(rs.get("source_room_id") or "").strip() + ] + # Prefer relays whose start falls inside the studio window ±2h + near = [] + for rs in day_relays: + rs_st = float(rs.get("started_at") or 0) + if st - 7200 <= rs_st <= en + 7200: + near.append(rs) + pick = near or day_relays + for rs in pick[:3]: + rid = str(rs.get("source_room_id") or "").strip() + if rid: + existing.add(rid) + an = str(rs.get("anchor_name") or "").strip() + if an: + anchors.add(an) + matched.append( + { + "id": rs.get("id"), + "started_at": rs.get("started_at"), + "ended_at": rs.get("ended_at"), + "duration_seconds": rs.get("duration_seconds"), + "status": rs.get("status"), + "source_room_id": rid, + "source_url": rs.get("source_url"), + "anchor_name": rs.get("anchor_name"), + "stream_title": rs.get("stream_title"), + "attrib": "same_day_fallback", + } + ) + s["relay_pushes"] = matched[:8] + s["source_rooms"] = sorted(existing) + s["anchors"] = sorted(anchors) + # also stamp onto minute_reports missing room + if existing: + rid0 = next(iter(existing)) + for mr in s.get("minute_reports") or []: + if not str(mr.get("source_room_id") or "").strip(): + mr["source_room_id"] = rid0 + # distribute studio viewer stats onto attributed rooms via session fields already set + + # Synthetic sessions from relay-only pushes (no Studio room attribution) + covered_relay_ids = set() + for s in studio_sessions: + for rp in s.get("relay_pushes") or []: + if rp.get("id") is not None: + covered_relay_ids.add(int(rp["id"])) + relay_only_sessions: list[dict[str, Any]] = [] + for rs in relay_rows: + rid = str(rs.get("source_room_id") or "").strip() + if not rid: + continue + try: + rsid = int(rs.get("id") or 0) + except (TypeError, ValueError): + rsid = 0 + if rsid and rsid in covered_relay_ids: + continue + st = float(rs.get("started_at") or 0) + if st <= 0: + continue + en = float(rs.get("ended_at") or 0) or st + dur = float(rs.get("duration_seconds") or max(0.0, en - st)) + from .timeutil import push_date_from_ts as _pd + + relay_only_sessions.append( + { + "id": f"relay-{rsid or int(st)}", + "started_at": st, + "ended_at": en, + "push_date": str(rs.get("push_date") or _pd(st)), + "duration_sec": dur, + "sample_count": 0, + "minute_count": 0, + "peak_viewers": None, + "avg_viewers": None, + "end_viewers": None, + "start_viewers": None, + "max_total_views": None, + "start_total_views": None, + "end_total_views": None, + "max_likes": None, + "live_duration": "", + "on_air_ratio": 0.0, + "source_rooms": [rid], + "anchors": [str(rs.get("anchor_name") or "").strip()] if rs.get("anchor_name") else [], + "stream_titles": [str(rs.get("stream_title") or "").strip()] if rs.get("stream_title") else [], + "neko_kinds": [], + "relay_session_uuids": [str(rs.get("session_uuid") or "")] if rs.get("session_uuid") else [], + "healths": [], + "live_statuses": [str(rs.get("status") or "")], + "source_url": str(rs.get("source_url") or ""), + "studio_url": "", + "detect_sources": ["relay"], + "minute_reports": [], + "relay_pushes": [ + { + "id": rs.get("id"), + "started_at": rs.get("started_at"), + "ended_at": rs.get("ended_at"), + "duration_seconds": rs.get("duration_seconds"), + "status": rs.get("status"), + "source_room_id": rid, + "anchor_name": rs.get("anchor_name"), + } + ], + } + ) + + ranking_sessions = studio_sessions + relay_only_sessions + source_rankings = source_performance_from_sessions( + ranking_sessions, + group_id=gid, + channel_name=str(g.get("name") or ""), + youtube_channel_id=ycid, + ) + source_rankings = merge_pool_sources_into_rankings(source_rankings, g) + + # Planning slots: top hours across measured sources + slot_votes: dict[int, dict[str, Any]] = { + h: {"hour": h, "sources": [], "best_peak": None, "best_avg_proxy": 0.0} for h in range(24) + } + for src in source_rankings: + if not src.get("measured"): + continue + for bh in src.get("best_hours") or []: + h = int(bh.get("hour") or 0) + slot_votes[h]["sources"].append( + { + "room_id": src.get("room_id"), + "anchor_name": src.get("anchor_name"), + "cover_url": src.get("cover_url"), + "peak_viewers": bh.get("peak_viewers"), + "live_minutes": bh.get("live_minutes"), + "score": src.get("score"), + } + ) + pk = bh.get("peak_viewers") + if pk is not None: + cur = slot_votes[h]["best_peak"] + slot_votes[h]["best_peak"] = int(pk) if cur is None else max(int(cur), int(pk)) + planning_slots = [] + for h in range(24): + row = slot_votes[h] + row["sources"] = sorted( + row["sources"], + key=lambda x: (int(x.get("peak_viewers") or 0), float(x.get("score") or 0)), + reverse=True, + )[:5] + if row["sources"]: + planning_slots.append(row) + planning_slots.sort(key=lambda x: int(x.get("best_peak") or 0), reverse=True) + + # Overview KPIs + all_peaks = [int(s["peak_viewers"]) for s in studio_sessions if s.get("peak_viewers") is not None] + all_avgs = [float(s["avg_viewers"]) for s in studio_sessions if s.get("avg_viewers") is not None] + all_totals = [int(s["max_total_views"]) for s in studio_sessions if s.get("max_total_views") is not None] + live_sec = sum(float(s.get("duration_sec") or 0) for s in studio_sessions) + latest = studio_sessions[0] if studio_sessions else None + measured = [r for r in source_rankings if r.get("measured")] + + pool = g.get("pool") or [] + featured = g.get("featured") or [] + slots = g.get("slots") or [] + + return { + "ok": True, + "group": { + "id": gid, + "name": g.get("name"), + "channel_pk": g.get("channel_pk"), + "youtube_channel_id": g.get("youtube_channel_id"), + "category": g.get("category"), + "time_slot_armed": g.get("time_slot_armed"), + "neko_instance_id": g.get("neko_instance_id"), + "neko_enabled": g.get("neko_enabled"), + "neko_open_prefer": g.get("neko_open_prefer"), + "ops_neko_bind": g.get("ops_neko_bind"), + "has_stream_key": bool(g.get("has_stream_key") or g.get("stream_key")), + "pool_count": len(pool) if isinstance(pool, list) else 0, + "featured_count": len(featured) if isinstance(featured, list) else 0, + "slot_count": len(slots) if isinstance(slots, list) else 0, + "pool": pool if isinstance(pool, list) else [], + "featured": featured if isinstance(featured, list) else [], + }, + "window": { + "days": days_n, + "since_ts": since, + "sample_count": len(samples), + "generated_at": time.time(), + "today": push_date_from_ts(time.time()), + }, + "overview": { + "session_count": len(studio_sessions), + "live_sec": round(live_sec, 1), + "live_hours": round(live_sec / 3600.0, 2), + "peak_viewers": max(all_peaks) if all_peaks else None, + "avg_viewers": round(sum(all_avgs) / len(all_avgs), 1) if all_avgs else None, + "max_total_views": max(all_totals) if all_totals else None, + "relay_push_count": len(relay_rows), + "unique_rooms": len(measured), + "top_source": measured[0] if measured else None, + "latest_session": ( + { + "started_at": latest.get("started_at"), + "ended_at": latest.get("ended_at"), + "peak_viewers": latest.get("peak_viewers"), + "end_viewers": latest.get("end_viewers"), + "max_total_views": latest.get("max_total_views"), + "live_duration": latest.get("live_duration"), + "anchors": latest.get("anchors"), + "source_rooms": latest.get("source_rooms"), + } + if latest + else None + ), + }, + "source_rankings": source_rankings, + "planning_slots": planning_slots, + "daily": daily, + "hours": hours, + "rooms": rooms, + "studio_sessions": studio_sessions, + "relay_sessions": relay_rows, + "relay_stats": relay_stats, + } diff --git a/backend/neko/browser-launch.sh b/backend/neko/browser-launch.sh index 08e678b..b73f586 100644 --- a/backend/neko/browser-launch.sh +++ b/backend/neko/browser-launch.sh @@ -384,15 +384,34 @@ launch_browser() { --disable-default-apps \ --disable-translate \ --metrics-recording-only \ - --no-default-browser-check + --no-default-browser-check \ + --renderer-process-limit=1 \ + --process-per-site \ + --disk-cache-size=1 \ + --media-cache-size=1 \ + --disable-features=IsolateOrigins,site-per-process,TranslateUI,BackForwardCache,WebAssemblySimd,WebAssemblyLazyCompilation,OptimizationGuideModelDownloading,OptimizationHints,PageContentAnnotations,PassageEmbeddings,WebAssembly,CalculateNativeWinOcclusion,CanvasOopRasterization,Vulkan,UseSkiaRenderer,InterestFeedContentSuggestions,OfflineAutoFetch,HeavyAdIntervention,AutofillServerCommunication,DialMediaRouteProvider \ + --js-flags="--max-old-space-size=160 --jitless --no-opt" \ + --disable-background-networking \ + --disable-component-update \ + --disable-sync \ + --disable-notifications \ + --mute-audio \ + --autoplay-policy=user-gesture-required \ + --memory-model=low if [ -n "$launch_window_flag" ]; then set -- "$@" "$launch_window_flag" fi if [ -n "$launch_url" ]; then set -- "$@" "$launch_url" fi + # Prefer host OOM killer keep Chrome over API/ffmpeg (negative = protected). + # Mask AVX512-ish paths that SIGILL on some colo CPUs / Chrome builds + export OPENSSL_ia32cap="~0x200000200000000" + export CHROME_FORCE_WAKE_ON_LAN=0 + echo -800 > /proc/self/oom_score_adj 2>/dev/null || true "$@" & browser_pid=$! + echo -900 > "/proc/${browser_pid}/oom_score_adj" 2>/dev/null || true } visible_window_count() { @@ -430,12 +449,21 @@ focus_live_studio_tab_once() { python3 - <<'PY' import json import time +import urllib.parse import urllib.request def fetch_tabs(): with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as resp: return json.loads(resp.read().decode("utf-8", "replace")) +def close_tab(tid: str) -> None: + if not tid: + return + try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2) + except Exception: + pass + for _ in range(40): try: tabs = fetch_tabs() @@ -446,44 +474,126 @@ else: raise SystemExit(0) def is_live(url: str) -> bool: - return "studio.youtube.com" in url and "livestreaming" in url + u = (url or "").lower() + return "studio.youtube.com" in u and "livestreaming" in u -def is_junk(url: str) -> bool: - return any( - x in url - for x in ( - "tampermonkey.net/changelog", - "tampermonkey.net/installed", - "accounts.google.com/ServiceLogin", - "accounts.google.com/v3/signin", - "accounts.google.com/accountchooser", - "accounts.google.com/RotateCookiesPage", - ) - ) +def is_keep(url: str) -> bool: + u = (url or "").lower() + if is_live(u): + return True + # Keep mid-login flows only. + if "accounts.google.com" in u and any(x in u for x in ("signin", "accountchooser", "identifier", "challenge", "servicelogin")): + return True + return False -live = [t for t in tabs if is_live(t.get("url") or "")] -for tab in tabs: - if not is_junk(tab.get("url") or ""): +pages = [t for t in tabs if (t.get("type") or "") == "page"] +live = [t for t in pages if is_live(t.get("url") or "")] +# Close every non-essential page (google.com / mail / random youtube / duplicates). +keep_live_id = (live[0].get("id") if live else "") or "" +for tab in pages: + url = tab.get("url") or "" + tid = tab.get("id") or "" + if keep_live_id and tid == keep_live_id: continue - tid = tab.get("id") + if is_live(url) and keep_live_id and tid != keep_live_id: + close_tab(tid) + continue + if is_keep(url): + continue + close_tab(tid) + +if keep_live_id: + try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{keep_live_id}", timeout=2) + except Exception: + pass +PY +} + +# Periodic GC: close junk tabs + soft-reload Studio Live to reclaim V8 heap. +prune_and_soft_reload_studio() { + case "${NEKO_STUDIO_MEM_GC:-1}" in + 0|false|FALSE|off|OFF|disable|disabled) + return 0 + ;; + esac + command -v python3 >/dev/null 2>&1 || return 0 + DO_RELOAD="${1:-0}" python3 - <<'PY' +import json +import os +import time +import urllib.parse +import urllib.request + +def fetch_tabs(): + with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as resp: + return json.loads(resp.read().decode("utf-8", "replace")) + +def close_tab(tid: str) -> None: if not tid: - continue + return try: urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2) except Exception: pass -if not live: +def is_live(url: str) -> bool: + u = (url or "").lower() + return "studio.youtube.com" in u and "livestreaming" in u + +def is_keep(url: str) -> bool: + u = (url or "").lower() + if is_live(u): + return True + if "accounts.google.com" in u and any(x in u for x in ("signin", "accountchooser", "identifier", "challenge", "servicelogin")): + return True + return False + +try: + tabs = fetch_tabs() +except Exception: raise SystemExit(0) -target = live[0] -tid = target.get("id") -if not tid: - raise SystemExit(0) -try: - urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=2) -except Exception: - pass +pages = [t for t in tabs if (t.get("type") or "") == "page"] +live = [t for t in pages if is_live(t.get("url") or "")] +keep_live = live[0] if live else None +keep_id = (keep_live or {}).get("id") or "" +keep_url = (keep_live or {}).get("url") or "" + +for tab in pages: + tid = tab.get("id") or "" + url = tab.get("url") or "" + if keep_id and tid == keep_id: + continue + if is_live(url) and keep_id and tid != keep_id: + close_tab(tid) + continue + if is_keep(url): + continue + close_tab(tid) + +do_reload = str(os.environ.get("DO_RELOAD") or "0").strip() in {"1", "true", "TRUE", "yes"} +if do_reload and keep_url: + try: + q = urllib.parse.quote(keep_url, safe="") + urllib.request.urlopen(f"http://127.0.0.1:9222/json/new?{q}", timeout=5) + time.sleep(2.5) + tabs2 = fetch_tabs() + lives = [t for t in tabs2 if (t.get("type") or "") == "page" and is_live(t.get("url") or "")] + # Keep newest live tab; close older duplicates. + for tab in lives[:-1]: + close_tab(tab.get("id") or "") + if lives: + tid = lives[-1].get("id") or "" + if tid: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=2) + except Exception: + pass +elif keep_id: + try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{keep_id}", timeout=2) + except Exception: + pass PY } @@ -542,6 +652,10 @@ while :; do focused_live_tab=0 startup_misses=0 closed_misses=0 + loop_ticks=0 + # ~90s prune; ~12min soft-reload (sleep 2 per tick) + prune_every="${NEKO_STUDIO_PRUNE_TICKS:-45}" + reload_every="${NEKO_STUDIO_RELOAD_TICKS:-360}" while kill -0 "$browser_pid" 2>/dev/null; do if browser_healthy; then if [ "$focused_live_tab" -eq 0 ]; then @@ -551,6 +665,22 @@ while :; do seen_window=1 startup_misses=0 closed_misses=0 + loop_ticks=$((loop_ticks + 1)) + if [ "$loop_ticks" -gt 0 ] && [ $((loop_ticks % prune_every)) -eq 0 ]; then + # Default: only prune junk tabs. Soft-reload Studio is OPT-IN + # (NEKO_STUDIO_SOFT_RELOAD=1) — never touch the RTMP push path; + # soft-reload is Studio UI only and is disabled to avoid any ops risk + # near live recommendation / stream continuity. + do_reload=0 + case "${NEKO_STUDIO_SOFT_RELOAD:-0}" in + 1|true|TRUE|yes|YES|on|ON) + if [ $((loop_ticks % reload_every)) -eq 0 ]; then + do_reload=1 + fi + ;; + esac + prune_and_soft_reload_studio "$do_reload" || true + fi else if [ "$seen_window" -eq 0 ]; then startup_misses=$((startup_misses + 1)) diff --git a/backend/neko/cdp_end_stream.py b/backend/neko/cdp_end_stream.py new file mode 100644 index 0000000..4397733 --- /dev/null +++ b/backend/neko/cdp_end_stream.py @@ -0,0 +1,341 @@ +# -*- coding: utf-8 -*- +"""CDP: click YouTube Studio End Stream (+ confirm dialog End) inside Neko Chrome. + +Handles the modal: + End Stream + Your stream will stop immediately... + [Not yet] [End] + +Run via: docker exec -i python3 - < this file +Prints one JSON line to stdout. +""" +from __future__ import annotations + +import base64 +import json +import os +import socket +import struct +import time +import urllib.request + + +def ws_connect(url: str) -> socket.socket: + assert url.startswith("ws://"), url + hostport, path = url[5:].split("/", 1) + path = "/" + path + host, port_s = hostport.split(":") + port = int(port_s) + key = base64.b64encode(os.urandom(16)).decode() + sock = socket.create_connection((host, port), timeout=8) + req = ( + f"GET {path} HTTP/1.1\r\n" + f"Host: {hostport}\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\n" + "Sec-WebSocket-Version: 13\r\n" + "\r\n" + ).encode() + sock.sendall(req) + buf = b"" + while b"\r\n\r\n" not in buf: + chunk = sock.recv(4096) + if not chunk: + raise RuntimeError("ws handshake closed") + buf += chunk + return sock + + +def ws_send(sock: socket.socket, payload: dict) -> None: + data = json.dumps(payload).encode() + mask = os.urandom(4) + header = bytearray([0x81]) + n = len(data) + if n < 126: + header.append(0x80 | n) + elif n < 65536: + header.append(0x80 | 126) + header.extend(struct.pack("!H", n)) + else: + header.append(0x80 | 127) + header.extend(struct.pack("!Q", n)) + header.extend(mask) + masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) + sock.sendall(bytes(header) + masked) + + +def ws_recv(sock: socket.socket): + def readexact(n: int) -> bytes: + out = b"" + while len(out) < n: + chunk = sock.recv(n - len(out)) + if not chunk: + raise RuntimeError("ws closed") + out += chunk + return out + + hdr = readexact(2) + b1, b2 = hdr[0], hdr[1] + opcode = b1 & 0x0F + masked = (b2 & 0x80) != 0 + ln = b2 & 0x7F + if ln == 126: + ln = struct.unpack("!H", readexact(2))[0] + elif ln == 127: + ln = struct.unpack("!Q", readexact(8))[0] + mask = readexact(4) if masked else b"" + data = readexact(ln) + if masked: + data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) + if opcode == 0x8: + return None + if opcode != 0x1: + return {"id": None} + return json.loads(data.decode()) + + +def eval_js(sock: socket.socket, expression: str, *, req_id: int, timeout: float = 6.0): + ws_send( + sock, + { + "id": req_id, + "method": "Runtime.evaluate", + "params": { + "expression": expression, + "returnByValue": True, + "awaitPromise": True, + }, + }, + ) + deadline = time.time() + timeout + while time.time() < deadline: + msg = ws_recv(sock) + if not msg: + break + if msg.get("id") == req_id: + return ((msg.get("result") or {}).get("result") or {}).get("value") + return None + + +CLICK_JS = r""" +(() => { + const END_RE = /^(end stream|stop streaming|结束直播|停止直播)$/i; + const CANCEL_RE = /not yet|not now|cancel|keep|继续|取消|还没有/i; + + function visible(el) { + if (!el || !el.getBoundingClientRect) return false; + const r = el.getBoundingClientRect(); + if (r.width < 2 || r.height < 2) return false; + const st = window.getComputedStyle ? getComputedStyle(el) : null; + if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false; + return true; + } + function* deepNodes(root) { + const stack = [root]; + while (stack.length) { + const n = stack.pop(); + if (!n) continue; + yield n; + if (n.shadowRoot) stack.push(n.shadowRoot); + if (n.children) { + for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]); + } + } + } + function labelOf(el) { + return String( + el.getAttribute?.('aria-label') || el.innerText || el.textContent || el.value || '' + ).replace(/\s+/g, ' ').trim(); + } + function fireClick(el) { + try { el.focus?.(); } catch (_) {} + try { + el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window})); + } catch (_) {} + try { el.click(); } catch (_) {} + } + for (const el of deepNodes(document)) { + if (!el || !el.tagName) continue; + const tag = String(el.tagName || '').toLowerCase(); + const role = String(el.getAttribute?.('role') || '').toLowerCase(); + const ok = + tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' || + tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button'; + if (!ok || !visible(el)) continue; + const t = labelOf(el); + if (!t || t.length > 48) continue; + if (CANCEL_RE.test(t)) continue; + if (!END_RE.test(t)) continue; + fireClick(el); + return {ok: true, text: t.slice(0, 40), needConfirm: true}; + } + return {ok: false, error: 'not_found'}; +})() +""" + +CONFIRM_JS = r""" +(() => { + // Dialog only: [Not yet] [End] — NEVER match header "End Stream" + const CONFIRM_EXACT = /^(end|结束)$/i; + const CANCEL_RE = /not yet|not now|cancel|keep|go back|还没有|取消|继续|稍后再说|end stream|结束直播|stop streaming/i; + + function visible(el) { + if (!el || !el.getBoundingClientRect) return false; + const r = el.getBoundingClientRect(); + if (r.width < 2 || r.height < 2) return false; + const st = window.getComputedStyle ? getComputedStyle(el) : null; + if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false; + return true; + } + function* deepNodes(root) { + const stack = [root]; + while (stack.length) { + const n = stack.pop(); + if (!n) continue; + yield n; + if (n.shadowRoot) stack.push(n.shadowRoot); + if (n.children) { + for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]); + } + } + } + function labelOf(el) { + return String( + el.getAttribute?.('aria-label') || el.innerText || el.textContent || '' + ).replace(/\s+/g, ' ').trim(); + } + function isClickable(el) { + if (!el || !el.tagName) return false; + const tag = String(el.tagName || '').toLowerCase(); + const role = String(el.getAttribute?.('role') || '').toLowerCase(); + return ( + tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' || + tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button' + ); + } + function fireClick(el) { + try { el.focus?.(); } catch (_) {} + try { + el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window})); + el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window})); + } catch (_) {} + try { el.click(); } catch (_) {} + } + + let roots = [document]; + for (const el of deepNodes(document)) { + const role = String(el.getAttribute?.('role') || '').toLowerCase(); + const tag = String(el.tagName || '').toLowerCase(); + if (role === 'dialog' || tag.includes('dialog')) { + roots.unshift(el); + if (el.shadowRoot) roots.unshift(el.shadowRoot); + } + } + + const exactHits = []; + for (const root of roots) { + for (const el of deepNodes(root)) { + if (!isClickable(el) || !visible(el)) continue; + const t = labelOf(el); + if (!t || t.length > 64) continue; + // Reject any control whose label contains End Stream / Not yet noise. + if (/end stream|结束直播|stop streaming|not yet/i.test(t) && !CONFIRM_EXACT.test(t.trim())) continue; + const compact = t.replace(/\s+/g, ' ').trim(); + if (CONFIRM_EXACT.test(compact)) exactHits.push([el, compact, 'label']); + else { + const leaf = String(el.innerText || '').replace(/\s+/g, ' ').trim(); + if (leaf && CONFIRM_EXACT.test(leaf) && leaf.length <= 8) exactHits.push([el, leaf, 'leaf']); + } + } + } + // Prefer hits found under a dialog root. + const pick = exactHits[0]; + if (!pick) return {ok: false, error: 'confirm_not_found', dialog_hint: roots.length > 1}; + fireClick(pick[0]); + return {ok: true, text: pick[1].slice(0, 40), via: pick[2]}; +})() +""" + + +def main() -> None: + tabs = json.loads( + urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode() + ) + live = [] + for t in tabs: + u = (t.get("url") or "").lower() + if "studio.youtube.com" in u and "livestreaming" in u: + live.append(t) + if not live: + print(json.dumps({"ok": False, "error": "no_live_tab"})) + return + tab = live[0] + ws_url = tab.get("webSocketDebuggerUrl") or "" + url = tab.get("url") or "" + if not ws_url: + print(json.dumps({"ok": False, "error": "no_ws", "url": url[:120]})) + return + + sock = ws_connect(ws_url) + try: + eval_js(sock, "true", req_id=1, timeout=3) + + def _is_dialog_end(row: dict) -> bool: + return bool(row.get("ok")) and str(row.get("text") or "").strip().lower() in { + "end", + "结束", + } + + # 1) Dialog already open → click exact "End" only (never header End Stream). + pre = eval_js(sock, CONFIRM_JS, req_id=2, timeout=8) or {} + if not isinstance(pre, dict): + pre = {"ok": False, "error": "bad_pre_confirm"} + first: dict = {"ok": False, "skipped": True} + confirm: dict = {"ok": False, "skipped": True} + if _is_dialog_end(pre): + confirm = pre + else: + # 2) Click header End Stream, then dialog End (retries). + first = eval_js(sock, CLICK_JS, req_id=3, timeout=8) or {} + if not isinstance(first, dict): + first = {"ok": False, "error": "bad_eval"} + if first.get("ok"): + confirm = {"ok": False, "error": "pending"} + for attempt, req_id in enumerate((4, 5, 6, 7), start=1): + time.sleep(1.6 if attempt == 1 else 1.0) + confirm = eval_js(sock, CONFIRM_JS, req_id=req_id, timeout=8) or {} + if not isinstance(confirm, dict): + confirm = {"ok": False, "error": "bad_confirm_eval"} + confirm["attempt"] = attempt + if _is_dialog_end(confirm): + break + confirm["ok"] = False + print( + json.dumps( + { + "ok": bool((first.get("ok") or _is_dialog_end(pre)) and _is_dialog_end(confirm)), + "url": url[:200], + "pre_confirm": pre, + "end_click": first, + "confirm_click": confirm, + }, + ensure_ascii=False, + ) + ) + finally: + try: + sock.close() + except Exception: + pass + + +if __name__ == "__main__": + main() diff --git a/backend/neko/cdp_studio_scrape.py b/backend/neko/cdp_studio_scrape.py index 4012c0a..d17e38a 100644 --- a/backend/neko/cdp_studio_scrape.py +++ b/backend/neko/cdp_studio_scrape.py @@ -164,6 +164,12 @@ def main() -> None: nodata = bool( re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower) ) + preparing = bool( + re.search( + r"preparing\s+stream|preparing\s+your\s+stream|准备(?:直播)?流|正在准备(?:直播|流)", + lower, + ) + ) session_live = bool( re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?", lower) or re.search(r"(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}", text) @@ -178,9 +184,20 @@ def main() -> None: lower, ) ) + # Control-room chrome loaded (not blank SPA shell). + control_ready = bool( + re.search( + r"end stream|stop streaming|结束直播|connect your encoder|stream health|stream settings|" + r"stream key|streamkey|待开播|等待你开始|直播设置|推流码", + lower, + ) + ) status = "" - if re.search(r"stream ended|直播已结束", lower) and not session_live: + if preparing: + # Preview spinner — NEVER treat as ready/on-air even if Excellent already shows. + status = "preparing" + elif re.search(r"stream ended|直播已结束", lower) and not session_live: status = "ended" elif session_live and (nodata or encoder_lost_hint): # 断播: LIVE session still open, encoder dropped — NOT 待开播 @@ -261,16 +278,19 @@ def main() -> None: if live_duration and not session_live: session_live = True - if status in {"", "waiting"} and (nodata or encoder_lost_hint): + if preparing: + status = "preparing" + elif status in {"", "waiting"} and (nodata or encoder_lost_hint): status = "encoder_lost" elif status in {"", "waiting"}: status = "live" - # 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播. - on_air = bool(status == "live" and not nodata and not encoder_lost_hint) + # 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播. Preparing ≠ 开播. + on_air = bool(status == "live" and not nodata and not encoder_lost_hint and not preparing) encoder_lost = status == "encoder_lost" or (session_live and nodata) encoder_receiving = bool( - not nodata + not preparing + and not nodata and not encoder_lost and ( status == "live" @@ -291,6 +311,8 @@ def main() -> None: "live_duration_sec": live_duration_sec, "on_air": on_air, "nodata": nodata, + "preparing_stream": preparing, + "control_ready": control_ready, "encoder_receiving": encoder_receiving, "encoder_lost": encoder_lost, "session_live": bool(session_live or status in {"live", "encoder_lost"}), diff --git a/backend/neko/live-ops-extension/content.js b/backend/neko/live-ops-extension/content.js index 698760f..a344369 100644 --- a/backend/neko/live-ops-extension/content.js +++ b/backend/neko/live-ops-extension/content.js @@ -1,6 +1,7 @@ -const LIVE_HUB_MIN_INTERVAL_MS = 1800; +const LIVE_HUB_MIN_INTERVAL_MS = 4000; let lastSentAt = 0; let lastSignature = ""; +let observerQueued = false; function cleanText(value, max = 260) { return String(value || "") @@ -9,6 +10,43 @@ function cleanText(value, max = 260) { .slice(0, max); } +/** Pause Studio preview videos / mute — biggest RAM leak on livestreaming page. */ +function tameMedia() { + try { + document.querySelectorAll("video, audio").forEach((el) => { + try { + el.muted = true; + el.pause(); + // Keep element for UI, but stop decoding frames. + if (typeof el.disablePictureInPicture === "boolean") el.disablePictureInPicture = true; + } catch (_) {} + }); + } catch (_) {} +} + +function injectMemCss() { + if (document.getElementById("livehub-mem-css")) return; + const style = document.createElement("style"); + style.id = "livehub-mem-css"; + style.textContent = ` + /* Shrink heavy Live Control Room surfaces on low-RAM Neko hosts */ + ytls-live-dashboard-section-renderer video, + ytls-stream-preview-section-renderer video, + #preview-player video, + .html5-video-player video { + max-height: 180px !important; + object-fit: contain !important; + } + ytls-live-dashboard-chart, + ytcp-ve[class*="chart"], + [class*="analytics-chart"] { + max-height: 120px !important; + overflow: hidden !important; + } + `; + (document.head || document.documentElement).appendChild(style); +} + function pageText() { return cleanText(document.body?.innerText || "", 6000); } @@ -278,9 +316,23 @@ function sendTelemetry(force = false) { }); } -const observer = new MutationObserver(() => sendTelemetry(false)); -observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true }); +const observer = new MutationObserver(() => { + if (observerQueued) return; + observerQueued = true; + setTimeout(() => { + observerQueued = false; + sendTelemetry(false); + }, 2500); +}); +// characterData on Studio Live fires constantly (viewer ticks) and burns RAM/CPU. +observer.observe(document.documentElement, { subtree: true, childList: true }); window.addEventListener("focus", () => sendTelemetry(true)); document.addEventListener("visibilitychange", () => sendTelemetry(true)); -setInterval(() => sendTelemetry(false), 3000); +injectMemCss(); +tameMedia(); +setInterval(() => { + injectMemCss(); + tameMedia(); + sendTelemetry(false); +}, 8000); sendTelemetry(true); diff --git a/backend/neko/live-ops-extension/manifest.json b/backend/neko/live-ops-extension/manifest.json index 64d2ecd..f665ada 100644 --- a/backend/neko/live-ops-extension/manifest.json +++ b/backend/neko/live-ops-extension/manifest.json @@ -1,8 +1,8 @@ { "manifest_version": 3, "name": "Live Hub YouTube Studio Telemetry", - "version": "1.3.0", - "description": "Captures YouTube Studio live status, viewer signals, stream health, and popups for the LAN Live Hub.", + "version": "1.4.0", + "description": "Captures YouTube Studio live telemetry; pauses preview media to limit Neko Chrome RAM.", "permissions": ["storage", "tabs"], "host_permissions": [ "https://studio.youtube.com/*", diff --git a/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json b/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json index 8f65eb8..da4e2fe 100644 --- a/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json +++ b/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json @@ -29,7 +29,9 @@ }, "default_locale": "en", "description": "__MSG_extDescription__", - "host_permissions": [ "\u003Call_urls>" ], + "host_permissions": [ + "" + ], "icons": { "128": "images/icon128.png", "32": "images/icon.png", @@ -41,17 +43,36 @@ "minimum_chrome_version": "120", "name": "__MSG_extName__", "offline_enabled": true, - "optional_permissions": [ "downloads" ], + "optional_permissions": [ + "downloads" + ], "options_page": "options.html", "options_ui": { "open_in_tab": true, "page": "options.html" }, - "permissions": [ "notifications", "unlimitedStorage", "tabs", "idle", "webNavigation", "webRequest", "webRequestBlocking", "storage", "contextMenus", "chrome://favicon/", "clipboardWrite", "cookies", "alarms", "declarativeNetRequestWithHostAccess", "scripting", "userScripts", "offscreen" ], + "permissions": [ + "notifications", + "unlimitedStorage", + "tabs", + "idle", + "webNavigation", + "webRequest", + "webRequestBlocking", + "storage", + "contextMenus", + "chrome://favicon/", + "clipboardWrite", + "cookies", + "alarms", + "declarativeNetRequestWithHostAccess", + "scripting", + "userScripts", + "offscreen" + ], "short_name": "__MSG_extShortName__", "storage": { "managed_schema": "schema.json" }, - "update_url": "https://clients2.google.com/service/update2/crx", "version": "5.5.0" } diff --git a/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG b/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG index a5bee42..dc2235e 100644 --- a/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG +++ b/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG @@ -1,3 +1,3 @@ -2026/05/19-04:29:50.026 4f Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001 -2026/05/19-04:29:50.026 4f Recovering log #3 -2026/05/19-04:29:50.027 4f Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log +2026/09/11-10:09:37.478 96 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001 +2026/09/11-10:09:37.479 96 Recovering log #3 +2026/09/11-10:09:37.479 96 Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log diff --git a/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG.old b/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG.old index e0724c0..d9258fb 100644 --- a/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG.old +++ b/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOG.old @@ -1,3 +1,2 @@ -2026/05/19-04:24:19.314 57 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001 -2026/05/19-04:24:19.315 57 Recovering log #3 -2026/05/19-04:24:19.315 57 Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log +2026/09/04-23:20:49.903 145 Creating DB /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo since it was missing. +2026/09/04-23:20:49.934 145 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001 diff --git a/backend/neko/tampermonkey-seed/Default/Preferences b/backend/neko/tampermonkey-seed/Default/Preferences index 8a0d651..13d1bb2 100644 --- a/backend/neko/tampermonkey-seed/Default/Preferences +++ b/backend/neko/tampermonkey-seed/Default/Preferences @@ -1 +1 @@ -{"extensions":{"settings":{"dhdgffkkebhmkfjojejmpbldmpobfkfo":{"account_extension_type":0,"ack_external":true,"active_permissions":{"api":["alarms","clipboardWrite","contextMenus","cookies","idle","notifications","storage","tabs","unlimitedStorage","webNavigation","webRequest","webRequestBlocking","scripting","declarativeNetRequestWithHostAccess","offscreen","userScripts"],"explicit_host":[""],"manifest_permissions":[],"scriptable_host":[]},"commands":{"open-dashboard":{"suggested_key":""},"open-dashboard-with-running-scripts":{"suggested_key":""},"open-new-script":{"suggested_key":""},"toggle-enable":{"suggested_key":""}},"content_settings":[],"creation_flags":9,"filtered_service_worker_events":{"webNavigation.onBeforeNavigate":[{"url":[{"schemes":["http","https"]}]}],"webNavigation.onCommitted":[{}]},"first_install_time":"13423454050276444","from_webstore":true,"incognito_content_settings":[],"incognito_preferences":{},"last_update_time":"13423454050276444","lastpingday":"13423388400889902","location":7,"manifest":{"action":{"default_icon":{"16":"images/icon_grey16.png","19":"images/icon_grey19.png","24":"images/icon_grey24.png","32":"images/icon_grey32.png","38":"images/icon_grey38.png"},"default_popup":"action.html","default_title":"Tampermonkey"},"background":{"service_worker":"background.js"},"commands":{"open-dashboard":{"description":"Open dashboard"},"open-dashboard-with-running-scripts":{"description":"Open dashboard with the current tab's URL used as filter"},"open-new-script":{"description":"Open new script tab"},"toggle-enable":{"description":"Toggle enable state"}},"current_locale":"en_US","default_locale":"en","description":"Change the web at will with userscripts","host_permissions":[""],"icons":{"128":"images/icon128.png","32":"images/icon.png","48":"images/icon48.png"},"incognito":"split","key":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjiyuc6OWY8gaVTe+b16fH2BBe0PQLMeUpEXSQvyv5a/6OiQ1D8bBLTfLvApD3zT2MZoXWu2KUILdkyg5OC/Tru8m+Js6e3RjHY9Rqbvnh8CJQgTJ+63L5w9aLsTvA2fqdDfhw8Mnl1GMcJd/RI/ZiBEm0stog0ZfyQjD1jpSEXQIDAQAB","manifest_version":3,"minimum_chrome_version":"120","name":"Tampermonkey","offline_enabled":true,"optional_permissions":["downloads"],"options_page":"options.html","options_ui":{"open_in_tab":true,"page":"options.html"},"permissions":["notifications","unlimitedStorage","tabs","idle","webNavigation","webRequest","webRequestBlocking","storage","contextMenus","chrome://favicon/","clipboardWrite","cookies","alarms","declarativeNetRequestWithHostAccess","scripting","userScripts","offscreen"],"short_name":"Tampermonkey","storage":{"managed_schema":"schema.json"},"update_url":"https://clients2.google.com/service/update2/crx","version":"5.5.0"},"path":"dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0","persistent_script_url_patterns":[""],"preferences":{},"regular_only_preferences":{},"service_worker_registration_info":{"version":"5.5.0"},"serviceworkerevents":["alarms.onAlarm","commands.onCommand","contextMenus.onClicked","notifications.onClicked","notifications.onClosed","notifications.onPermissionLevelChanged","permissions.onAdded","permissions.onRemoved","runtime.onConnectExternal","runtime.onInstalled","runtime.onUpdateAvailable","storage.onChanged","tabs.onActivated","tabs.onRemoved","tabs.onReplaced","tabs.onUpdated","webRequest.onBeforeRequest/s1","webRequest.onErrorOccurred/s4","webRequest.onHeadersReceived/s2","webRequest.onResponseStarted/s3"],"state":1,"uninstall_url":"https://www.tampermonkey.net/uninstall.php?ext=dhdg","user_scripts_worlds":{"configuration":{"_default":{"csp":"script-src 'self' 'unsafe-inline' *","messaging":true}}},"was_installed_by_default":false,"was_installed_by_oem":false}}}} \ No newline at end of file +{"extensions":{"settings":{"dhdgffkkebhmkfjojejmpbldmpobfkfo":{"account_extension_type":0,"active_permissions":{"api":["alarms","clipboardWrite","contextMenus","cookies","idle","notifications","storage","tabs","unlimitedStorage","webNavigation","webRequest","webRequestBlocking","scripting","declarativeNetRequestWithHostAccess","offscreen","userScripts"],"explicit_host":[""],"manifest_permissions":[],"scriptable_host":[]},"commands":{"open-dashboard":{"suggested_key":""},"open-dashboard-with-running-scripts":{"suggested_key":""},"open-new-script":{"suggested_key":""},"toggle-enable":{"suggested_key":""}},"content_settings":[],"creation_flags":9,"filtered_service_worker_events":{"webNavigation.onBeforeNavigate":[{"url":[{"schemes":["http","https"]}]}],"webNavigation.onCommitted":[{}]},"first_install_time":"13423454050276444","from_webstore":false,"incognito_content_settings":[],"incognito_preferences":{},"last_update_time":"13423454050276444","lastpingday":"13423388400889902","location":4,"manifest":{"action":{"default_icon":{"16":"images/icon_grey16.png","19":"images/icon_grey19.png","24":"images/icon_grey24.png","32":"images/icon_grey32.png","38":"images/icon_grey38.png"},"default_popup":"action.html","default_title":"Tampermonkey"},"background":{"service_worker":"background.js"},"commands":{"open-dashboard":{"description":"Open dashboard"},"open-dashboard-with-running-scripts":{"description":"Open dashboard with the current tab's URL used as filter"},"open-new-script":{"description":"Open new script tab"},"toggle-enable":{"description":"Toggle enable state"}},"current_locale":"en_US","default_locale":"en","description":"Change the web at will with userscripts","host_permissions":[""],"icons":{"128":"images/icon128.png","32":"images/icon.png","48":"images/icon48.png"},"incognito":"split","key":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjiyuc6OWY8gaVTe+b16fH2BBe0PQLMeUpEXSQvyv5a/6OiQ1D8bBLTfLvApD3zT2MZoXWu2KUILdkyg5OC/Tru8m+Js6e3RjHY9Rqbvnh8CJQgTJ+63L5w9aLsTvA2fqdDfhw8Mnl1GMcJd/RI/ZiBEm0stog0ZfyQjD1jpSEXQIDAQAB","manifest_version":3,"minimum_chrome_version":"120","name":"Tampermonkey","offline_enabled":true,"optional_permissions":["downloads"],"options_page":"options.html","options_ui":{"open_in_tab":true,"page":"options.html"},"permissions":["notifications","unlimitedStorage","tabs","idle","webNavigation","webRequest","webRequestBlocking","storage","contextMenus","chrome://favicon/","clipboardWrite","cookies","alarms","declarativeNetRequestWithHostAccess","scripting","userScripts","offscreen"],"short_name":"Tampermonkey","storage":{"managed_schema":"schema.json"},"version":"5.5.0"},"path":"dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0","persistent_script_url_patterns":[""],"preferences":{},"regular_only_preferences":{},"service_worker_registration_info":{"version":"5.5.0"},"serviceworkerevents":["alarms.onAlarm","commands.onCommand","contextMenus.onClicked","notifications.onClicked","notifications.onClosed","notifications.onPermissionLevelChanged","permissions.onAdded","permissions.onRemoved","runtime.onConnectExternal","runtime.onInstalled","runtime.onUpdateAvailable","storage.onChanged","tabs.onActivated","tabs.onRemoved","tabs.onReplaced","tabs.onUpdated","webRequest.onBeforeRequest/s1","webRequest.onErrorOccurred/s4","webRequest.onHeadersReceived/s2","webRequest.onResponseStarted/s3"],"state":1,"uninstall_url":"https://www.tampermonkey.net/uninstall.php?ext=dhdg","user_scripts_worlds":{"configuration":{"_default":{"csp":"script-src 'self' 'unsafe-inline' *","messaging":true}}},"was_installed_by_default":false,"was_installed_by_oem":false}}}} \ No newline at end of file diff --git a/backend/tests/test_assign_category.py b/backend/tests/test_assign_category.py index be24936..d852caf 100644 --- a/backend/tests/test_assign_category.py +++ b/backend/tests/test_assign_category.py @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*- -from app.yt_assign_db import group_is_time_slot, normalize_assign_category +from app.yt_assign_db import ( + group_eligible_for_time_slot, + group_is_time_slot, + group_time_slot_armed, + normalize_assign_category, +) def test_normalize_assign_category(): @@ -19,3 +24,25 @@ def test_group_is_time_slot(): assert group_is_time_slot({"category": "普通"}) is False assert group_is_time_slot({}) is False assert group_is_time_slot(None) is False + + +def test_group_time_slot_armed_default_true(): + assert group_time_slot_armed({}) is True + assert group_time_slot_armed({"time_slot_armed": 1}) is True + assert group_time_slot_armed({"time_slot_armed": 0}) is False + assert group_time_slot_armed({"time_slot_armed": False}) is False + assert group_time_slot_armed({"time_slot_armed": "false"}) is False + + +def test_group_eligible_for_time_slot(): + base = { + "enabled": True, + "category": "time_slot", + "has_stream_key": True, + "time_slot_armed": True, + } + assert group_eligible_for_time_slot(base) is True + assert group_eligible_for_time_slot({**base, "time_slot_armed": False}) is False + assert group_eligible_for_time_slot({**base, "has_stream_key": False}) is False + assert group_eligible_for_time_slot({**base, "category": "normal"}) is False + assert group_eligible_for_time_slot({**base, "enabled": False}) is False diff --git a/backend/tests/test_cdp_poll_running_disabled.py b/backend/tests/test_cdp_poll_running_disabled.py new file mode 100644 index 0000000..482141e --- /dev/null +++ b/backend/tests/test_cdp_poll_running_disabled.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Unit: CDP poll includes running-but-disabled Nekos.""" +from __future__ import annotations + +from app import youtube_neko as yn +from app import yt_assign_db + + +def test_cdp_poll_ids_include_running_disabled(monkeypatch): + groups = [ + {"neko_enabled": True, "neko_instance_id": 1}, + {"neko_enabled": False, "neko_instance_id": 6}, + {"neko_enabled": False, "neko_instance_id": 9}, + ] + + def fake_state(nid, check_http=False): + return {"running": nid == 6} + + monkeypatch.setattr(yt_assign_db, "list_groups", lambda include_urls=False: groups) + monkeypatch.setattr(yn, "_container_state", fake_state) + ids = yn._neko_ids_for_cdp_poll() + assert 1 in ids + assert 6 in ids + assert 9 not in ids diff --git a/backend/tests/test_complete_live_broadcast.py b/backend/tests/test_complete_live_broadcast.py new file mode 100644 index 0000000..a41f470 --- /dev/null +++ b/backend/tests/test_complete_live_broadcast.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +"""Unit: complete_active_live_broadcast filters lifeCycleStatus.""" +from __future__ import annotations + +import asyncio +from typing import Any + +from app import youtube_manage + + +def test_complete_active_live_broadcast_completes_live(monkeypatch): + async def fake_access(pk: str): + return "tok", {"id": pk} + + calls: list[dict[str, Any]] = [] + + async def fake_get(path: str, *, token: str, params: dict[str, Any]): + assert path == "liveBroadcasts" + return { + "items": [ + {"id": "vid_live", "status": {"lifeCycleStatus": "live"}}, + {"id": "vid_complete", "status": {"lifeCycleStatus": "complete"}}, + {"id": "vid_ready", "status": {"lifeCycleStatus": "ready"}}, + ] + } + + async def fake_post(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]): + calls.append({"path": path, "params": params}) + return {"id": params.get("id"), "status": {"lifeCycleStatus": "complete"}} + + monkeypatch.setattr(youtube_manage, "_access_for_channel", fake_access) + monkeypatch.setattr(youtube_manage, "_get", fake_get) + monkeypatch.setattr(youtube_manage, "_post", fake_post) + + out = asyncio.run(youtube_manage.complete_active_live_broadcast("ch1")) + assert out["completed"] == ["vid_live"] + assert calls and calls[0]["params"]["broadcastStatus"] == "complete" + + +def test_complete_empty_pk(): + out = asyncio.run(youtube_manage.complete_active_live_broadcast("")) + assert out["ok"] is False diff --git a/backend/tests/test_prefer_non_uhd_stream.py b/backend/tests/test_prefer_non_uhd_stream.py new file mode 100644 index 0000000..ea70ac3 --- /dev/null +++ b/backend/tests/test_prefer_non_uhd_stream.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +from app.douyin import pick_stream_candidates, _is_uhd_stream_url + + +def test_prefer_non_uhd_over_origin(): + room = { + "stream_url": { + "flv_pull_url": { + "ORIGIN": "http://cdn.example/stream_uhd.flv?unique_id=x_flv_uhd", + "FULL_HD1": "http://cdn.example/stream_full.flv?unique_id=x_flv", + "HD1": "http://cdn.example/stream_hd.flv?unique_id=x_hd_flv", + "SD1": "http://cdn.example/stream_sd.flv", + } + } + } + cands = pick_stream_candidates(room) + assert cands[0] == "http://cdn.example/stream_hd.flv?unique_id=x_hd_flv" + assert cands[1] == "http://cdn.example/stream_full.flv?unique_id=x_flv" + assert cands[-1].endswith("_uhd") or "_uhd" in cands[-1] + + +def test_demote_uhd_even_if_only_labeled_hd(): + room = { + "stream_url": { + "flv_pull_url": { + "HD1": "http://cdn.example/foo_uhd.flv", + "SD1": "http://cdn.example/foo_sd.flv", + } + } + } + cands = pick_stream_candidates(room) + assert cands[0] == "http://cdn.example/foo_sd.flv" + assert _is_uhd_stream_url(cands[-1]) + + +def test_uhd_only_still_usable(): + room = { + "stream_url": { + "flv_pull_url": { + "ORIGIN": "http://cdn.example/only_uhd.flv", + } + } + } + cands = pick_stream_candidates(room) + assert len(cands) == 1 + assert "uhd" in cands[0] diff --git a/backend/tests/test_preparing_stream_gate.py b/backend/tests/test_preparing_stream_gate.py new file mode 100644 index 0000000..80af50e --- /dev/null +++ b/backend/tests/test_preparing_stream_gate.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +"""Preparing stream must never count as on-air / ready for FFmpeg.""" +from __future__ import annotations + +from app import youtube_neko as yn + + +def test_payload_stream_confirmed_rejects_preparing(): + assert not yn._payload_stream_confirmed( + { + "live_status": "preparing", + "health": "excellent", + "text": "Preparing stream Excellent connection", + "signals": {"preparing_stream": True}, + } + ) + assert not yn._payload_stream_confirmed( + { + "live_status": "live", + "health": "excellent", + "text": "Preparing stream Excellent connection Stream is healthy", + } + ) + + +def test_payload_nodata_or_pending_includes_preparing(): + assert yn._payload_nodata_or_pending( + { + "live_status": "preparing", + "text": "Preparing stream", + "signals": {"preparing_stream": True}, + } + ) + + +def test_ffmpeg_pid_alive_helper(): + from app.youtube_relay_pipeline import _ffmpeg_pid_alive + import os + + assert _ffmpeg_pid_alive(0) is False + assert _ffmpeg_pid_alive(-1) is False + assert _ffmpeg_pid_alive(os.getpid()) is True diff --git a/backend/tests/test_relay_normal_auto.py b/backend/tests/test_relay_normal_auto.py new file mode 100644 index 0000000..b582724 --- /dev/null +++ b/backend/tests/test_relay_normal_auto.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Unit tests: normal auto candidates + first-live exclusive claim.""" +from __future__ import annotations + +from typing import Any + +from app.youtube_relay_pipeline import ( + _claim_first_live_normal, + _normal_auto_candidates, + pick_source_for_group, +) + + +def test_normal_auto_candidates_skips_timeslot(monkeypatch): + groups = [ + {"id": "n1", "enabled": 1, "category": "normal", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"}, + {"id": "t1", "enabled": 1, "category": "time_slot", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"}, + {"id": "n2", "enabled": 0, "category": "normal", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"}, + {"id": "n3", "enabled": 1, "category": "normal", "stream_key": ""}, + ] + out = _normal_auto_candidates(groups) + assert [g["id"] for g in out] == ["n1"] + + +def test_claim_first_live_normal_by_sort_order(monkeypatch): + live = {"r1", "r2"} + + def _live_ids(): + return set(live) + + monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", _live_ids) + + groups: list[dict[str, Any]] = [ + { + "id": "b", + "enabled": 1, + "category": "normal", + "sort_order": 20, + "stream_key": "k", + "featured": [{"url": "https://live.douyin.com/2", "room_id": "r2", "title": "B"}], + }, + { + "id": "a", + "enabled": 1, + "category": "normal", + "sort_order": 10, + "stream_key": "k", + "featured": [{"url": "https://live.douyin.com/1", "room_id": "r1", "title": "A"}], + }, + { + "id": "c", + "enabled": 1, + "category": "normal", + "sort_order": 5, + "stream_key": "k", + "featured": [{"url": "https://live.douyin.com/9", "room_id": "offline", "title": "C"}], + }, + ] + claimed = _claim_first_live_normal(groups) + assert claimed is not None + gid, g, src = claimed + assert gid == "a" + assert src["room_id"] == "r1" + + +def test_pick_source_normal_featured_prefer_live(monkeypatch): + monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", lambda: {"live1"}) + g = { + "id": "g1", + "enabled": 1, + "category": "normal", + "featured": [ + {"url": "https://live.douyin.com/off", "room_id": "off", "title": "off"}, + {"url": "https://live.douyin.com/live1", "room_id": "live1", "title": "on"}, + ], + } + src = pick_source_for_group(g, respect_schedule=False) + assert src and src["room_id"] == "live1" diff --git a/backend/tests/test_relay_paused_status.py b/backend/tests/test_relay_paused_status.py new file mode 100644 index 0000000..cee7dee --- /dev/null +++ b/backend/tests/test_relay_paused_status.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Regression: paused_* status must not show as「监听中」.""" +from __future__ import annotations + +from app.youtube_relay_status import summarize_relay_group + + +def test_summarize_paused_exclusive_not_monitoring(): + row = summarize_relay_group( + group={ + "id": "g1", + "enabled": True, + "has_stream_key": True, + "stream_key": "aaaa-bbbb-cccc-dddd-eeee", + "category": "normal", + "featured": [{"url": "https://live.douyin.com/1"}], + }, + st={ + "status": "paused_exclusive", + "error": "单路独占:当前仅允许 X 推流", + "recent_log": [], + }, + session_running=False, + pipeline_enabled=True, + time_slot_mode=False, + lane_armed=True, + ) + assert row["business_status"] == "paused_exclusive" + assert "独占" in (row.get("business_note") or "") + + +def test_summarize_paused_studio_not_monitoring(): + row = summarize_relay_group( + group={ + "id": "g1", + "enabled": True, + "has_stream_key": True, + "stream_key": "aaaa-bbbb-cccc-dddd-eeee", + "category": "normal", + "featured": [{"url": "https://live.douyin.com/1"}], + }, + st={ + "status": "paused_studio", + "error": "Studio 未 on_air 熔断中(约剩 5 分)", + "recent_log": [], + }, + session_running=False, + pipeline_enabled=True, + time_slot_mode=False, + lane_armed=True, + ) + assert row["business_status"] == "paused_studio" + assert "熔断" in (row.get("business_note") or "") diff --git a/backend/tests/test_shorts_gap_rules.py b/backend/tests/test_shorts_gap_rules.py new file mode 100644 index 0000000..1215697 --- /dev/null +++ b/backend/tests/test_shorts_gap_rules.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +"""Unit tests for Shorts front-load pace (90% by BJ 20:00) + gap floors.""" +from __future__ import annotations + +import time +from unittest import mock + +from app.shorts_schedule import ( + CHANNEL_GAP_FLOOR_SEC, + QUOTA_DEADLINE_HOUR, + QUOTA_FRONTLOAD_RATIO, + _deadline_ts, + _quota_pressure, + fleet_pace_plan, + pick_upload_at, +) +from app.timeutil import beijing_day_bounds, push_date_from_ts + + +def test_channel_gap_floor_constant(): + assert CHANNEL_GAP_FLOOR_SEC == 600.0 + assert QUOTA_DEADLINE_HOUR == 20 + assert QUOTA_FRONTLOAD_RATIO == 0.9 + + +def test_deadline_is_beijing_20(): + day = push_date_from_ts(time.time()) + day_start, day_end = beijing_day_bounds(day) + d = _deadline_ts(day) + assert day_start < d < day_end + assert abs(d - (day_start + 20 * 3600)) < 60 + + +def test_pick_upload_at_respects_10min_floor(temp_db): + ch = temp_db.create_shorts_channel(name="Gap", daily_min=9, daily_max=9, enabled=True) + day = push_date_from_ts(time.time()) + noon = beijing_day_bounds(day)[0] + 12 * 3600 + # Seed enough uploads so we are NOT behind front-load (avoid emergency <10min). + for i in range(8): + j = temp_db.create_shorts_job(session_id="", room_id=f"gap{i}", channel_pk=ch["id"], push_date=day) + temp_db.update_shorts_job( + j["id"], status="done", finished_at=noon - 3600 + i * 700, upload_at=noon - 3600 + i * 700 + ) + j = temp_db.create_shorts_job(session_id="", room_id="gapx", channel_pk=ch["id"], push_date=day) + temp_db.update_shorts_job(j["id"], status="done", finished_at=noon - 30, upload_at=noon - 30) + + cfg = { + "shorts_upload_spread": True, + "shorts_upload_min_gap_sec": 600, + "shorts_channel_min_gap_sec": 600, + } + with mock.patch("app.shorts_schedule.time.time", return_value=noon): + at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg) + assert at >= noon - 30 + CHANNEL_GAP_FLOOR_SEC + + +def test_pick_upload_at_stays_before_deadline_when_behind(temp_db): + ch = temp_db.create_shorts_channel(name="Early", daily_min=9, daily_max=9, enabled=True) + day = push_date_from_ts(time.time()) + day_start, _ = beijing_day_bounds(day) + now = day_start + 6 * 3600 # 06:00 BJ — far behind 90% by 20:00 + deadline = _deadline_ts(day) + cfg = { + "shorts_upload_spread": True, + "shorts_upload_min_gap_sec": 600, + "shorts_channel_min_gap_sec": 600, + } + with mock.patch("app.shorts_schedule.time.time", return_value=now): + at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg) + assert at <= deadline + 60 + assert at < day_start + 22 * 3600 # not dumped near midnight + + +def test_end_of_day_compresses_below_10min(temp_db): + ch = temp_db.create_shorts_channel(name="Rush", daily_min=9, daily_max=9, enabled=True) + day = push_date_from_ts(time.time()) + _, day_end = beijing_day_bounds(day) + now = day_end - 12 * 60 + j = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"], push_date=day) + temp_db.update_shorts_job(j["id"], status="uploaded", finished_at=now - 20, upload_at=now - 20) + cfg = { + "shorts_upload_spread": True, + "shorts_upload_min_gap_sec": 600, + "shorts_channel_min_gap_sec": 600, + } + with mock.patch("app.shorts_schedule.time.time", return_value=now): + at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg) + assert at < now + CHANNEL_GAP_FLOOR_SEC + assert at <= day_end + + +def test_quota_pressure_uses_channel_daily_min(temp_db): + ch = temp_db.create_shorts_channel(name="P", daily_min=9, daily_max=12, enabled=True) + day = push_date_from_ts(time.time()) + g, c, behind, urgent = _quota_pressure(channel_pk=ch["id"], push_date=day, now=time.time()) + assert behind is True or urgent is True or g < 1.0 + assert c <= 1.0 + + +def test_fleet_pace_plan_behind_in_morning(temp_db): + for i in range(3): + temp_db.create_shorts_channel(name=f"C{i}", daily_min=9, daily_max=9, enabled=True) + day = push_date_from_ts(time.time()) + day_start, _ = beijing_day_bounds(day) + now = day_start + 6 * 3600 + with mock.patch("app.shorts_schedule.time.time", return_value=now): + plan = fleet_pace_plan(day, now=now) + assert plan["front_target"] == 25 or plan["front_target"] >= 24 # ceil(0.9*27)=25 + assert plan["behind"] is True + assert plan["recommended_global_gap_sec"] <= 600 diff --git a/backend/tests/test_shorts_quota.py b/backend/tests/test_shorts_quota.py index 81f3f1d..4b62fd5 100644 --- a/backend/tests/test_shorts_quota.py +++ b/backend/tests/test_shorts_quota.py @@ -23,6 +23,7 @@ def test_shorts_quota_counts_scheduled(temp_db): ) temp_db.update_shorts_job(job["id"], status="scheduled", upload_at=time.time() + 3600) assert temp_db.shorts_channel_upload_count(ch["id"], day) == 2 + assert temp_db.shorts_channel_uploaded_count(ch["id"], day) == 0 def test_pick_shorts_channel_prefers_under_min(temp_db): @@ -30,7 +31,8 @@ def test_pick_shorts_channel_prefers_under_min(temp_db): ch2 = temp_db.create_shorts_channel(name="B", daily_min=5, daily_max=9, enabled=True) day = push_date_from_ts(time.time()) for i in range(5): - temp_db.create_shorts_job(session_id="", room_id=f"a{i}", channel_pk=ch1["id"], push_date=day) + job = temp_db.create_shorts_job(session_id="", room_id=f"a{i}", channel_pk=ch1["id"], push_date=day) + temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time()) picked = temp_db.pick_shorts_channel(day) assert picked is not None assert picked["id"] == ch2["id"] @@ -40,15 +42,34 @@ def test_quota_gap_and_summary(temp_db): ch = temp_db.create_shorts_channel(name="G", daily_min=5, daily_max=9, enabled=True) day = push_date_from_ts(time.time()) for i in range(3): - temp_db.create_shorts_job(session_id="", room_id=f"g{i}", channel_pk=ch["id"], push_date=day) + job = temp_db.create_shorts_job(session_id="", room_id=f"g{i}", channel_pk=ch["id"], push_date=day) + temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time()) summary = temp_db.shorts_channels_quota_summary(day) assert len(summary) == 1 assert summary[0]["used"] == 3 + assert summary[0]["uploaded"] == 3 assert summary[0]["gap"] == 6 assert summary[0]["min_met"] is False assert temp_db.shorts_total_quota_gap(day) == 6 +def test_quota_progress_ignores_pending(temp_db): + ch = temp_db.create_shorts_channel(name="P", daily_min=9, daily_max=9, enabled=True) + day = push_date_from_ts(time.time()) + for i in range(2): + job = temp_db.create_shorts_job(session_id="", room_id=f"up{i}", channel_pk=ch["id"], push_date=day) + temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time()) + for i in range(7): + temp_db.create_shorts_job(session_id="", room_id=f"pe{i}", channel_pk=ch["id"], push_date=day) + summary = temp_db.shorts_channels_quota_summary(day)[0] + assert summary["uploaded"] == 2 + assert summary["used"] == 2 + assert summary["pipeline"] == 9 + assert summary["gap"] == 7 + assert summary["max_met"] is False + assert summary["pipeline_full"] is True + + def test_beijing_day_bounds(): day = push_date_from_ts(time.time()) start, end = beijing_day_bounds(day) diff --git a/backend/tests/test_shorts_room_offsets.py b/backend/tests/test_shorts_room_offsets.py new file mode 100644 index 0000000..434d877 --- /dev/null +++ b/backend/tests/test_shorts_room_offsets.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +"""Test multi-channel same-room with distinct clip offsets.""" +from __future__ import annotations + +import time + +from app.timeutil import push_date_from_ts + + +def test_same_room_multi_channel_offsets(temp_db): + day = push_date_from_ts(time.time()) + ch_a = temp_db.create_shorts_channel(name="A", daily_min=9, daily_max=9, enabled=True) + ch_b = temp_db.create_shorts_channel(name="B", daily_min=9, daily_max=9, enabled=True) + ch_c = temp_db.create_shorts_channel(name="C", daily_min=9, daily_max=9, enabled=True) + + off0 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15) + assert off0 == 0 + j1 = temp_db.create_shorts_job( + session_id="", + room_id="roomX", + channel_pk=ch_a["id"], + push_date=day, + clip_offset_sec=off0, + ) + assert j1 is not None + assert float(j1.get("clip_offset_sec") or 0) == 0 + + off1 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15) + assert off1 == 15 + j2 = temp_db.create_shorts_job( + session_id="", + room_id="roomX", + channel_pk=ch_b["id"], + push_date=day, + clip_offset_sec=off1, + ) + assert j2 is not None + assert float(j2.get("clip_offset_sec") or 0) == 15 + + off2 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15) + assert off2 == 30 + j3 = temp_db.create_shorts_job( + session_id="", + room_id="roomX", + channel_pk=ch_c["id"], + push_date=day, + clip_offset_sec=off2, + ) + assert j3 is not None + + # Same channel cannot reuse same room + j_dup = temp_db.create_shorts_job( + session_id="", + room_id="roomX", + channel_pk=ch_a["id"], + push_date=day, + clip_offset_sec=45, + ) + assert j_dup is None + + +def test_legacy_global_dedupe_still_works(temp_db): + day = push_date_from_ts(time.time()) + ch_a = temp_db.create_shorts_channel(name="A2", daily_min=9, daily_max=9, enabled=True) + ch_b = temp_db.create_shorts_channel(name="B2", daily_min=9, daily_max=9, enabled=True) + j1 = temp_db.create_shorts_job( + session_id="", + room_id="roomY", + channel_pk=ch_a["id"], + push_date=day, + dedupe_room_global=True, + ) + assert j1 is not None + j2 = temp_db.create_shorts_job( + session_id="", + room_id="roomY", + channel_pk=ch_b["id"], + push_date=day, + dedupe_room_global=True, + ) + assert j2 is None diff --git a/backend/tests/test_shorts_yt_quota.py b/backend/tests/test_shorts_yt_quota.py index 9950f3d..f597c2c 100644 --- a/backend/tests/test_shorts_yt_quota.py +++ b/backend/tests/test_shorts_yt_quota.py @@ -8,6 +8,8 @@ from app.shorts_yt_quota import ( YT_DAILY_UPLOAD_LIMIT_DEFAULT, blocked_profile_ids, clear_all_upload_self_blocks, + defer_profile_shorts_uploads, + mark_api_quota_cooldown, pause_uploads_until_reset, profile_upload_blocked, project_uploads_available, @@ -34,8 +36,8 @@ def test_yt_upload_budget_and_reserve(temp_db): assert remaining2 == remaining - 1 -def test_never_self_blocks_uploads(temp_db): - """Local counter / pause helpers must not gate uploads.""" +def test_local_counter_does_not_block(temp_db): + """Burning the local display counter must not gate uploads by itself.""" cfg = temp_db.get_settings_map() for _ in range(YT_DAILY_UPLOAD_LIMIT_DEFAULT + 5): assert reserve_yt_upload_slot(cfg) is True @@ -44,20 +46,43 @@ def test_never_self_blocks_uploads(temp_db): assert profile_upload_blocked(cfg, profile_id="A") == (False, 0.0) assert blocked_profile_ids(cfg) == set() - ch = temp_db.create_shorts_channel(name="Y", enabled=True) + +def test_api_cooldown_blocks_and_ntfy_once(temp_db): + """Real API cool-down blocks auto path; second mark in-window should not re-notify.""" + cfg = temp_db.get_settings_map() + until1, notify1 = mark_api_quota_cooldown(cfg, profile_id="B", reason="429 test") + assert notify1 is True + assert until1 > time.time() + cfg = temp_db.get_settings_map() + blocked, until = profile_upload_blocked(cfg, profile_id="B") + assert blocked is True + assert until > time.time() + assert "B" in blocked_profile_ids(cfg) + assert project_uploads_available(cfg, profile_id="B") is False + # Other clients stay open + assert project_uploads_available(cfg, profile_id="A") is True + + until2, notify2 = mark_api_quota_cooldown(cfg, profile_id="B", reason="429 again") + assert notify2 is False + assert until2 >= until1 - 1 + + +def test_api_cooldown_defers_due_jobs(temp_db): + ch = temp_db.create_shorts_channel(name="YB", enabled=True, oauth_profile_id="B") job = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"]) - temp_db.update_shorts_job(job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=time.time()) - until = pause_uploads_until_reset(temp_db.get_settings_map(), reason="test pause") + now = time.time() + temp_db.update_shorts_job( + job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=now - 10 + ) + until = pause_uploads_until_reset(temp_db.get_settings_map(), profile_id="B", reason="test") + moved = defer_profile_shorts_uploads("B", until, reason="cool") + assert moved >= 1 refreshed = temp_db.get_shorts_job(job["id"]) assert refreshed is not None - assert refreshed["status"] == "scheduled" - # Must NOT defer the job into the future as a self-pause - assert float(refreshed["upload_at"]) <= time.time() + 5 - cfg = temp_db.get_settings_map() - assert float(cfg.get("shorts_yt_upload_blocked_until") or 0) == 0 - assert until > time.time() # reset timestamp still returned for UI hint - clear_all_upload_self_blocks(cfg) - assert profile_upload_blocked(temp_db.get_settings_map(), profile_id="A") == (False, 0.0) + assert float(refreshed["upload_at"]) >= until + # clear_all only drops expired cool-downs + clear_all_upload_self_blocks(temp_db.get_settings_map()) + assert profile_upload_blocked(temp_db.get_settings_map(), profile_id="B")[0] is True def test_pacific_day_from_ts(): diff --git a/backend/tests/test_studio_snap_evidence_first.py b/backend/tests/test_studio_snap_evidence_first.py new file mode 100644 index 0000000..0bd0af4 --- /dev/null +++ b/backend/tests/test_studio_snap_evidence_first.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""studio_snapshot_for_group: evidence-first when one side has Live UI.""" +from __future__ import annotations + +from app import youtube_neko as yn + + +def test_prefers_remote_live_over_fresh_local_closed(monkeypatch): + local = { + "live_page_open": False, + "on_air": False, + "age_sec": 5.0, + "received_at": 1.0, + "ui_source": "local", + "neko_kind": "local", + "viewer_count": None, + } + remote = { + "live_page_open": True, + "on_air": True, + "age_sec": 8.0, + "received_at": 1.0, + "ui_source": "remote", + "neko_kind": "remote", + "viewer_count": 3, + "url": "https://studio.youtube.com/video/x/livestreaming", + } + + monkeypatch.setattr( + yn, + "studio_snapshot_for_ref", + lambda *a, **k: dict(remote), + ) + monkeypatch.setattr( + yn, + "studio_snapshot_for_instance", + lambda *a, **k: dict(local), + ) + g = { + "neko_open_prefer": "local", + "ops_neko_open_url": "https://example/neko/19/", + "ops_neko_slot": 19, + "neko_instance_id": 3, + } + snap = yn.studio_snapshot_for_group(g, max_age_sec=120.0, include_minute_reports=False) + assert snap.get("live_page_open") is True + assert snap.get("viewer_count") == 3 + assert str(snap.get("ui_source") or "").startswith("remote") + + +def test_prefer_remote_still_used_when_both_live(monkeypatch): + local = { + "live_page_open": True, + "on_air": True, + "age_sec": 5.0, + "received_at": 1.0, + "ui_source": "local", + "viewer_count": 1, + } + remote = { + "live_page_open": True, + "on_air": True, + "age_sec": 5.0, + "received_at": 1.0, + "ui_source": "remote", + "viewer_count": 9, + } + monkeypatch.setattr(yn, "studio_snapshot_for_ref", lambda *a, **k: dict(remote)) + monkeypatch.setattr(yn, "studio_snapshot_for_instance", lambda *a, **k: dict(local)) + g = { + "neko_open_prefer": "remote", + "ops_neko_open_url": "https://example/neko/19/", + "ops_neko_slot": 19, + "neko_instance_id": 3, + } + snap = yn.studio_snapshot_for_group(g, max_age_sec=120.0, include_minute_reports=False) + assert snap.get("viewer_count") == 9 diff --git a/backend/tests/test_timeslot_test_overlay.py b/backend/tests/test_timeslot_test_overlay.py new file mode 100644 index 0000000..4588aad --- /dev/null +++ b/backend/tests/test_timeslot_test_overlay.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from app.yt_assign_db import overlay_timeslot_test_schedule + + +def test_overlay_timeslot_test_marks_forced_active(): + sched = { + "channels": [ + {"group_id": "a", "active": True, "alias_group_ids": []}, + {"group_id": "b", "active": False, "alias_group_ids": ["b2"]}, + ] + } + out = overlay_timeslot_test_schedule(sched, test_on=True, test_group_id="b") + assert out["test_mode"] is True + assert out["test_group_id"] == "b" + by = {c["group_id"]: c for c in out["channels"]} + assert by["a"]["active"] is False + assert by["a"]["schedule_active"] is True + assert by["b"]["active"] is True + assert by["b"]["test_force"] is True + + +def test_overlay_timeslot_test_off_keeps_clock(): + sched = { + "channels": [ + {"group_id": "a", "active": True, "alias_group_ids": []}, + {"group_id": "b", "active": False, "alias_group_ids": []}, + ] + } + out = overlay_timeslot_test_schedule(sched, test_on=False, test_group_id="b") + assert out["test_mode"] is False + assert out["channels"][0]["active"] is True + assert out["channels"][1]["active"] is False diff --git a/backend/tests/test_youtube_live.py b/backend/tests/test_youtube_live.py index 6dbe9fe..1af0fd9 100644 --- a/backend/tests/test_youtube_live.py +++ b/backend/tests/test_youtube_live.py @@ -1,7 +1,14 @@ # -*- coding: utf-8 -*- from __future__ import annotations -from app.youtube_live import _live_entry, _parse_batch_result +import time + +from app.youtube_live import ( + _live_entry, + _parse_batch_result, + _studio_receiving_from_snap, + _studio_snap_belongs_to_assign_group, +) def test_parse_batch_live(): @@ -45,3 +52,84 @@ def test_parse_broadcast_shaped_as_search_not_required(): assert entry["is_live"] is False assert entry["channel_id"] == "UCabc" assert entry["source"] == "oauth-broadcast" + + +def test_studio_receiving_rejects_edge_mirror_and_preparing(): + assert not _studio_receiving_from_snap( + { + "on_air": True, + "encoder_receiving": True, + "live_status": "live", + "detect_source": "edge_assign_live", + "received_at": time.time(), + } + ) + assert not _studio_receiving_from_snap( + { + "on_air": True, + "preparing_stream": True, + "live_status": "preparing", + "detect_source": "cdp_dom", + "received_at": time.time(), + } + ) + assert not _studio_receiving_from_snap( + { + "on_air": True, + "live_status": "live", + "detect_source": "chrome_extension", + "received_at": time.time() - 120, + } + ) + assert _studio_receiving_from_snap( + { + "on_air": True, + "encoder_receiving": True, + "live_status": "live", + "detect_source": "chrome_extension", + "received_at": time.time() - 10, + } + ) + + +def test_studio_snap_shared_neko_requires_ownership(): + snap = { + "on_air": True, + "encoder_receiving": True, + "live_status": "live", + "url": "https://studio.youtube.com/video/pMQedt4HENo/livestreaming", + "detect_source": "chrome_extension", + "received_at": time.time() - 5, + } + # Sibling card on shared Neko, not pushing, wrong UC → must not claim receiving. + assert not _studio_snap_belongs_to_assign_group( + snap, + youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw", + neko_shared=True, + group_is_pushing=False, + ) + # Owner pushing on that Neko may claim it. + assert _studio_snap_belongs_to_assign_group( + snap, + youtube_channel_id="UCO9wMc9tj9mD221Gu0rLBeA", + neko_shared=True, + group_is_pushing=True, + ) + # Channel path in Studio URL binds unambiguously. + assert _studio_snap_belongs_to_assign_group( + { + **snap, + "url": "https://studio.youtube.com/channel/UCtVfMFdLTN4ap__8g7MFtVw/livestreaming", + }, + youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw", + neko_shared=True, + group_is_pushing=False, + ) + # Saved studio video hint matches snap URL. + assert _studio_snap_belongs_to_assign_group( + snap, + youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw", + neko_shared=True, + group_is_pushing=False, + studio_url_hint="https://studio.youtube.com/video/pMQedt4HENo/livestreaming", + ) \ No newline at end of file diff --git a/desktop/src/lib/douyinLive.ts b/desktop/src/lib/douyinLive.ts index 80fd459..4fbfc1f 100644 --- a/desktop/src/lib/douyinLive.ts +++ b/desktop/src/lib/douyinLive.ts @@ -1,4 +1,4 @@ -import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { fetchJson } from "@/lib/api"; import { useEventStream } from "@/lib/realtime"; @@ -30,12 +30,15 @@ const DouyinLiveContext = createContext<{ refresh: async () => {}, }); -export function useDouyinLiveProviderValue(intervalMs = 10000) { +export function useDouyinLiveProviderValue(intervalMs = 25000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); const { tick, last } = useEventStream(true); + const inFlight = useRef(false); const refresh = useCallback(async (silent = false) => { + if (inFlight.current) return; + inFlight.current = true; if (!silent) setLoading(true); try { const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap; @@ -43,13 +46,17 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) { } catch { /* keep last map */ } finally { + inFlight.current = false; if (!silent) setLoading(false); } }, []); useEffect(() => { void refresh(true); - const id = window.setInterval(() => void refresh(true), intervalMs); + const id = window.setInterval(() => { + if (document.hidden) return; + void refresh(true); + }, intervalMs); const onVis = () => { if (document.visibilityState === "visible") void refresh(true); }; @@ -63,6 +70,7 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) { useEffect(() => { if (!last?.kind) return; if (!["live", "offline", "risk"].includes(String(last.kind))) return; + if (document.hidden) return; void refresh(true); // eslint-disable-next-line react-hooks/exhaustive-deps }, [tick]); @@ -83,18 +91,21 @@ export function useDouyinLiveMap() { return useContext(DouyinLiveContext); } -export function useDouyinLiveEntry(roomId?: string, fallback?: DouyinLiveEntry | null): DouyinLiveEntry | null { +export function useDouyinLiveCount() { + const { map } = useDouyinLiveMap(); + return Number(map?.live_count || 0); +} + +export function useDouyinLiveEntry( + roomId?: string, + fallback?: DouyinLiveEntry | null, +): DouyinLiveEntry | null { const { map } = useDouyinLiveMap(); const rid = String(roomId || "").trim(); if (!rid) return fallback ?? null; return map?.entries?.[rid] ?? fallback ?? null; } -export function useDouyinLiveCount() { - const { map } = useDouyinLiveMap(); - return Number(map?.live_count || 0); -} - export function resolveDouyinLive(entry: DouyinLiveEntry | null | undefined, lastStatus?: string) { const status = String(entry?.last_status || lastStatus || "unknown").trim() || "unknown"; const isLive = entry?.is_live ?? status === "live"; diff --git a/desktop/src/lib/youtubeLive.ts b/desktop/src/lib/youtubeLive.ts index 0c32128..f000f40 100644 --- a/desktop/src/lib/youtubeLive.ts +++ b/desktop/src/lib/youtubeLive.ts @@ -46,6 +46,7 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); const [focused, setFocused] = useState(true); + const inFlight = useMemo(() => ({ current: false }), []); useEffect(() => { const unsub = window.desktop?.onWindowFocus?.((f) => setFocused(f)); @@ -58,6 +59,8 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) { }, []); const refresh = useCallback(async (silent = false) => { + if (inFlight.current) return; + inFlight.current = true; if (!silent) setLoading(true); try { const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap; @@ -65,9 +68,10 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) { } catch { /* keep last map */ } finally { + inFlight.current = false; if (!silent) setLoading(false); } - }, []); + }, [inFlight]); useEffect(() => { void refresh(true); diff --git a/desktop/src/pages/OverviewPage.tsx b/desktop/src/pages/OverviewPage.tsx index fe95259..2d58f06 100644 --- a/desktop/src/pages/OverviewPage.tsx +++ b/desktop/src/pages/OverviewPage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { Link } from "react-router-dom"; import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react"; @@ -111,6 +111,7 @@ export default function HomePage() { const now = useNow(1000); const { connected, last, tick } = useEventStream(false); // desktop: poll only — SSE was wedging Windows API const ytLiveCount = useYouTubeLiveCount(); + const silentTick = useRef(0); const load = useCallback(async (opts?: RefreshOpts) => { const silent = Boolean(opts?.silent); @@ -121,6 +122,26 @@ export default function HomePage() { try { const iso = todayBeijingISO(); const desktop = Boolean(window.desktop); + // Silent polls: mostly light (monitor + active); fat payload every 3rd tick. + const lightOnly = silent && silentTick.current++ % 3 !== 0; + if (lightOnly) { + const m = await fetchJson("/api/monitor/status?light=1").catch(() => + fetchJson("/api/monitor/status"), + ); + const a = await fetchJson("/api/sessions/active"); + setStatus(m); + const sessions = (a.sessions || []) as ActiveSession[]; + const seen = new Set(); + setActive( + sessions.filter((s) => { + const key = s.room_id || s.id; + if (!key || seen.has(key)) return false; + seen.add(key); + return true; + }), + ); + return; + } if (desktop) { // Windows desktop: serialize SQLite-backed API calls (avoid 20s timeouts) const m = await fetchJson("/api/monitor/status"); diff --git a/desktop/src/pages/SettingsPage.tsx b/desktop/src/pages/SettingsPage.tsx index 390c95e..74ded5c 100644 --- a/desktop/src/pages/SettingsPage.tsx +++ b/desktop/src/pages/SettingsPage.tsx @@ -785,7 +785,7 @@ function OpsPanel() { const refresh = useCallback(async () => { try { const [h, pb] = await Promise.all([ - fetchJson("/api/health"), + fetchJson("/api/health?detail=1"), fetchJson("/api/pb/health").catch(() => null), ]); setHealth(h); diff --git a/desktop/src/pages/ShortsPage.tsx b/desktop/src/pages/ShortsPage.tsx index 0708f2c..50373c4 100644 --- a/desktop/src/pages/ShortsPage.tsx +++ b/desktop/src/pages/ShortsPage.tsx @@ -59,6 +59,8 @@ type BoardChannel = { scheduled: number; uploaded: number; pending: number; + recorded?: number; + recording?: number; gap?: number; min_met?: boolean; max_met?: boolean; @@ -241,11 +243,16 @@ export default function ShortsPage() { const totals = useMemo(() => { const uploaded = boardChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = boardChannels.reduce((s, c) => s + (c.scheduled || 0), 0); - const used = boardChannels.reduce((s, c) => s + (c.used || 0), 0); + const recorded = boardChannels.reduce((s, c) => s + (c.recorded || 0), 0); + const pending = boardChannels.reduce((s, c) => s + (c.pending || 0), 0); + const recording = boardChannels.reduce((s, c) => s + (c.recording || 0), 0); + const used = uploaded; const cap = boardChannels.reduce((s, c) => s + (c.daily_max || 9), 0); const minTarget = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0); - const gap = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.used || 0))), 0); - return { uploaded, scheduled, used, cap, minTarget, gap }; + const gap = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0); + const queuedUpload = scheduled + recorded; + const pendingRecord = pending + recording; + return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap }; }, [boardChannels]); const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—"; @@ -258,7 +265,6 @@ export default function ShortsPage() { }>; async function probeOauth() { - setBusy(true); try { const r = await fetchJson("/api/shorts/oauth/probe", { method: "POST" }); const failed = Number(r.failed ?? 0); @@ -269,13 +275,10 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } async function toggle(enabled: boolean) { - setBusy(true); setMsg(""); try { await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" }); @@ -283,8 +286,6 @@ export default function ShortsPage() { await load(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -304,7 +305,6 @@ export default function ShortsPage() { } async function saveChannel(andAuth: boolean) { - setBusy(true); setMsg(""); setError(""); try { @@ -329,8 +329,6 @@ export default function ShortsPage() { } } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -369,7 +367,6 @@ export default function ShortsPage() { } async function runReconcile() { - setBusy(true); try { const r = await fetchJson("/api/shorts/reconcile", { method: "POST" }); toast.push( @@ -379,8 +376,6 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } @@ -398,7 +393,6 @@ export default function ShortsPage() { }); if (!ok) return; } - setBusy(true); try { const r = await fetchJson("/api/shorts/jobs/bulk", { method: "POST", @@ -409,8 +403,6 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } @@ -663,9 +655,9 @@ export default function ShortsPage() { <>
{[ - ["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "每频道强制 9 条/日"], + ["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "每频道强制 9 条/日"], ["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"], - ["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`], + ["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`], [ "抖音在播源", String(status?.douyin_live_count ?? "—"), @@ -714,7 +706,6 @@ export default function ShortsPage() { 开关
@@ -514,7 +498,6 @@ export default function YouTubePage() {
diff --git a/frontend/src/app/ops/mobile/page.tsx b/frontend/src/app/ops/mobile/page.tsx index 1ad1e60..a9f0d67 100644 --- a/frontend/src/app/ops/mobile/page.tsx +++ b/frontend/src/app/ops/mobile/page.tsx @@ -33,7 +33,7 @@ export default function OpsMobilePage() { setLoading(true); try { const [h, m] = await Promise.all([ - fetchJson("/api/health"), + fetchJson("/api/health?detail=1"), fetchJson("/api/ops/alerts/metrics"), ]); setHealth(h as Health); diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 95d9def..2ff2f6d 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -111,9 +111,11 @@ export default function HomePage() { const [opsBusy, setOpsBusy] = useState(""); const toast = useToast(); const confirm = useConfirm(); - const now = useNow(1000); + const now = useNow(5000); const { connected, last, tick } = useEventStream(true); const silentTickRef = useRef(0); + const connectedRef = useRef(connected); + connectedRef.current = connected; const ytLiveCount = useYouTubeLiveCount(); const { map: ytLiveMap } = useYouTubeLiveMap(); const ytLiveNav = useMemo(() => primaryYouTubeLiveNav(ytLiveMap), [ytLiveMap]); @@ -129,12 +131,13 @@ export default function HomePage() { if (silent) { silentTickRef.current += 1; const everyThird = silentTickRef.current % 3 === 0; + const sseOk = connectedRef.current; // Silent poll: skip fat rooms/day-sessions/stats; SSE feeds events when connected. const reqs: Promise[] = [ fetchJson("/api/monitor/status?light=1"), fetchJson("/api/sessions/active?platform=douyin"), ]; - if (!connected) { + if (!sseOk) { reqs.push(fetchJson("/api/events?limit=20&platform=douyin")); } if (everyThird) { @@ -145,7 +148,7 @@ export default function HomePage() { const m = results[i++] as MonitorStatus; setStatus((prev) => ({ ...(prev || {}), ...m } as MonitorStatus)); const a = results[i++] as { sessions?: ActiveSession[] }; - if (!connected) { + if (!sseOk) { const e = results[i++] as { events?: EventItem[] }; setEvents(e.events || []); } @@ -206,14 +209,14 @@ export default function HomePage() { } finally { if (!silent) setLoading(false); } - }, [connected]); + }, []); useEffect(() => { void load({ silent: false }); const t = setInterval(() => { if (document.hidden) return; void load({ silent: true }); - }, 25000); + }, 35000); const onVis = () => { if (!document.hidden) void load({ silent: true }); }; diff --git a/frontend/src/app/settings/page.tsx b/frontend/src/app/settings/page.tsx index 289c90e..f3264b2 100644 --- a/frontend/src/app/settings/page.tsx +++ b/frontend/src/app/settings/page.tsx @@ -1349,7 +1349,7 @@ function OpsPanel() { const refresh = useCallback(async () => { try { const [h, pb] = await Promise.all([ - fetchJson("/api/health"), + fetchJson("/api/health?detail=1"), fetchJson("/api/pb/health").catch(() => null), ]); setHealth(h); diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 04d9f4a..c49497c 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -86,6 +86,8 @@ type BoardChannel = { scheduled: number; uploaded: number; pending: number; + recorded?: number; + recording?: number; gap?: number; min_met?: boolean; max_met?: boolean; @@ -154,7 +156,20 @@ export default function ShortsPage() { const [jobTotal, setJobTotal] = useState(0); const [form, setForm] = useState({ ...emptyForm }); const [editId, setEditId] = useState(""); - const [busy, setBusy] = useState(false); + const [actionPending, setActionPending] = useState>({}); + const isPending = useCallback((key: string) => Boolean(actionPending[key]), [actionPending]); + const withPending = useCallback(async (key: string, fn: () => Promise) => { + setActionPending((p) => (p[key] ? p : { ...p, [key]: true })); + try { + await fn(); + } finally { + setActionPending((p) => { + const n = { ...p }; + delete n[key]; + return n; + }); + } + }, []); const [togglingId, setTogglingId] = useState(""); const [msg, setMsg] = useState(""); const [error, setError] = useState(""); @@ -179,10 +194,11 @@ export default function ShortsPage() { const { map: ytLiveMap } = useYouTubeLiveMap(); const load = useCallback( - async (opts?: { appendJobs?: boolean; jobOffset?: number }) => { + async (opts?: { appendJobs?: boolean; jobOffset?: number; soft?: boolean }) => { const appendJobs = Boolean(opts?.appendJobs); + const soft = Boolean(opts?.soft); if (appendJobs) setLoadingMoreJobs(true); - else setLoading(true); + else if (!soft) setLoading(true); try { const off = appendJobs ? Number(opts?.jobOffset ?? 0) : 0; const jobQs = new URLSearchParams({ limit: String(JOB_PAGE), offset: String(off) }); @@ -452,13 +468,18 @@ export default function ShortsPage() { const totals = useMemo(() => { const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0); - const used = displayChannels.reduce((s, c) => s + (c.used || 0), 0); + const recorded = displayChannels.reduce((s, c) => s + (c.recorded || 0), 0); + const pending = displayChannels.reduce((s, c) => s + (c.pending || 0), 0); + const recording = displayChannels.reduce((s, c) => s + (c.recording || 0), 0); + const used = uploaded; const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 9), 0); const minTarget = displayChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0); const gap = displayChannels .filter((c) => c.enabled !== false) - .reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.used || 0))), 0); - return { uploaded, scheduled, used, cap, minTarget, gap }; + .reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0); + const queuedUpload = scheduled + recorded; + const pendingRecord = pending + recording; + return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap }; }, [displayChannels]); const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—"; @@ -476,7 +497,6 @@ export default function ShortsPage() { } async function probeOauth() { - setBusy(true); try { const r = await fetchJson("/api/shorts/oauth/probe", { method: "POST" }); const failed = Number(r.failed ?? 0); @@ -487,13 +507,10 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } async function toggle(enabled: boolean) { - setBusy(true); setMsg(""); try { await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" }); @@ -501,8 +518,6 @@ export default function ShortsPage() { await load(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -529,7 +544,6 @@ export default function ShortsPage() { } async function saveChannel(andAuth: boolean) { - setBusy(true); setMsg(""); setError(""); try { @@ -572,8 +586,6 @@ export default function ShortsPage() { } } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -638,7 +650,11 @@ export default function ShortsPage() { } else { toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok"); } - await load(); + // Soft refresh: keep cards mounted; only this switch shows busy. + setChannels((prev) => + prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)), + ); + await load({ soft: true }); } catch (e) { toast.push((e as Error).message, "err"); } finally { @@ -653,7 +669,6 @@ export default function ShortsPage() { } async function runReconcile() { - setBusy(true); try { const r = await fetchJson("/api/shorts/reconcile", { method: "POST" }); toast.push( @@ -663,8 +678,6 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } @@ -682,7 +695,6 @@ export default function ShortsPage() { }); if (!ok) return; } - setBusy(true); try { const r = await fetchJson("/api/shorts/jobs/bulk", { method: "POST", @@ -693,8 +705,6 @@ export default function ShortsPage() { await load(); } catch (e) { toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } @@ -965,9 +975,9 @@ export default function ShortsPage() { <>
{[ - ["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"], + ["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"], ["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"], - ["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`], + ["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`], [ "抖音在播源", String(status?.douyin_live_count ?? "—"), @@ -976,7 +986,9 @@ export default function ShortsPage() { [ "错峰间隔", `≥${Math.round((status?.upload_min_gap_sec || 720) / 60)}分`, - `同频道 ≥${Math.round((status?.channel_min_gap_sec || 2400) / 60)}分 · 落后自动加速`, + status?.pace?.behind + ? `同频道 ≥${Math.round((status?.channel_min_gap_sec || 600) / 60)}分 · 目标20:00前90% · 落后加速中` + : `同频道 ≥${Math.round((status?.channel_min_gap_sec || 600) / 60)}分 · 目标20:00前90%`, ], ].map(([label, value, hint]) => (
@@ -1016,7 +1028,6 @@ export default function ShortsPage() { 开关
) : Array.isArray(status?.yt_quota_by_profile) ? ( @@ -1155,12 +1180,15 @@ export default function ShortsPage() { - Client {row.id} · {row.used}/{row.limit}(剩 {row.remaining}) + Client {row.id} · {row.used}/{row.limit} + {row.blocked ? " · 冷静中" : `(剩 ${row.remaining})`} ))}
@@ -1183,17 +1211,14 @@ export default function ShortsPage() { - @@ -265,7 +260,6 @@ export function ClipsPanel({ + ))} + + + + + +
+
+ Source → Channel Planning +
+

{g?.name || "频道排源"}

+

+ 核心问题:哪个抖音直播间在这个 YouTube 频道表现最好?哪个北京时段该开?用 Studio 同时观看/总观看/峰值给每个抖音源打分,指导排班与选源。 +

+ {top ? ( +
+
+ +
+
+
+ + 本频道最佳抖音源 + #{top.rank} · score {top.score} +
+

{top.anchor_name || top.room_id}

+ + {top.douyin_url?.replace(/^https?:\/\//, "")} + + +

{top.planning_tip}

+
+ 均 {fmtNum(top.avg_viewers)} + 峰 {fmtNum(top.peak_viewers)} + 总观 {fmtNum(top.max_total_views)} + {top.live_hours}h / {top.session_count}场 + {(top.best_hours || []).slice(0, 2).map((h) => ( + + {h.label} + + ))} +
+
+
+ ) : ( +

窗口内还没有可排名的抖音源 Studio 样本。开播并让 Neko 采样后会出现。

+ )} +
+ + {error ?
{error}
: null} + {loading && !data ? ( +
+ 汇总抖音源表现… +
+ ) : null} + + {data ? ( + <> +
+ + + + + +
+ +
+ {( + [ + ["sources", "抖音源排名", measured.length], + ["slots", "最佳时段", (data.planning_slots || []).length], + ["sessions", "场次", (data.studio_sessions || []).length], + ["daily", "每日", (data.daily || []).length], + ] as const + ).map(([id, label, count]) => ( + + ))} +
+ + {tab === "sources" ? ( +
+

按「排源分数」排序:均值同时 × 场次可信度 + 峰值 + 总观看 + 直播时长。展开看每源 24h 热力与建议开播点。

+ {measured.map((src) => { + const open = openRoom === src.room_id; + return ( +
+ + {open ? ( +
+

该源在本频道 · 北京 24 小时热力(直播分钟 / 峰值)

+
+ {(src.hour_heatmap || []).map((h) => { + const intensity = Number(h.live_minutes || 0) / maxHour; + return ( +
+
+

{String(h.hour).padStart(2, "0")}

+

{Math.round(h.live_minutes)}′

+

{fmtNum(h.peak_viewers)}

+
+ ); + })} +
+ {(src.stream_titles || []).length ? ( +

标题采样:{(src.stream_titles || []).join(" · ")}

+ ) : null} + {src.last_started_at ? ( +

最近关联 {fmtTs(src.last_started_at)}

+ ) : null} +
+ ) : null} +
+ ); + })} + + {unmeasured.length ? ( +
+

池/精选中尚未测到 Studio 数据的抖音源({unmeasured.length})

+
+ {unmeasured.map((src) => ( +
+
+ +
+
+

{src.anchor_name || src.room_id}

+ + {src.room_id} + +

未测 · 开播采样后进入排名

+
+
+ ))} +
+
+ ) : null} + {!measured.length && !unmeasured.length ? ( +
暂无抖音源关联数据
+ ) : null} +
+ ) : null} + + {tab === "slots" ? ( +
+

按北京小时汇总:该时段历史上哪几个抖音源在本频道峰值最高 — 用来排时间段推流。

+ {(data.planning_slots || []).map((slot) => ( +
+
+
+ + + {String(slot.hour).padStart(2, "0")}:00–{String((slot.hour + 1) % 24).padStart(2, "0")}:00 + + 北京 +
+ 时段峰 {fmtNum(slot.best_peak)} +
+
+ {(slot.sources || []).map((s, i) => ( +
+
+ +
+
+

{s.anchor_name || s.room_id}

+

{s.room_id}

+

峰 {fmtNum(s.peak_viewers)} · score {fmtNum(s.score as any)}

+
+
+ ))} +
+
+ ))} + {!data.planning_slots?.length ?

暂无时段建议

: null} +
+ ) : null} + + {tab === "sessions" ? ( +
+ {(data.studio_sessions || []).map((s: any) => { + const open = openSession === s.id; + return ( +
+ + {open ? ( +
+ +
+ ) : null} +
+ ); + })} +
+ ) : null} + + {tab === "daily" ? ( +
+ + + + + + + + + + + + + + {(data.daily || []).map((d: any) => ( + + + + + + + + + + ))} + +
日期场次时长峰均总观源
{d.date}{d.session_count}{d.live_hours}h{fmtNum(d.peak_viewers)}{fmtNum(d.avg_viewers)}{fmtNum(d.max_total_views)}{(d.anchors || []).join("、") || (d.rooms || []).join(",")}
+
+ ) : null} + + ) : null} +
+ + ); +} diff --git a/frontend/src/app/youtube/analytics/page.tsx b/frontend/src/app/youtube/analytics/page.tsx new file mode 100644 index 0000000..7efed9d --- /dev/null +++ b/frontend/src/app/youtube/analytics/page.tsx @@ -0,0 +1,240 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { ExternalLink, Loader2, RefreshCw, Sparkles, Trophy } from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { fetchJson, fmtTs } from "@/lib/api"; + +type Rec = { + rank: number; + room_id: string; + anchor_name?: string; + cover_url?: string; + douyin_url?: string; + group_id?: string; + channel_name?: string; + youtube_channel_id?: string; + score?: number; + avg_viewers?: number | null; + peak_viewers?: number | null; + max_total_views?: number | null; + live_hours?: number; + best_hours?: Array<{ label: string; peak_viewers?: number | null }>; + planning_tip?: string; +}; + +type RoomRow = { + room_id: string; + anchor_name?: string; + cover_url?: string; + douyin_url?: string; + best_channel?: Rec & { channel_name?: string; group_id?: string }; + channels: Array<{ + group_id?: string; + channel_name?: string; + score?: number; + avg_viewers?: number | null; + peak_viewers?: number | null; + best_hours?: Array<{ label: string }>; + }>; +}; + +function fmtNum(n: number | null | undefined): string { + if (n == null || !Number.isFinite(Number(n))) return "—"; + return Number(n).toLocaleString(); +} + +function Cover({ src, name }: { src?: string; name?: string }) { + const [broken, setBroken] = useState(false); + if (!src || broken) { + return ( +
+ {(name || "?").slice(0, 1)} +
+ ); + } + return ( + // eslint-disable-next-line @next/next/no-img-element + {name setBroken(true)} /> + ); +} + +export default function FleetSourceAnalyticsPage() { + const [days, setDays] = useState(30); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + const [recs, setRecs] = useState([]); + const [rooms, setRooms] = useState([]); + const [windowMeta, setWindowMeta] = useState | null>(null); + const [tab, setTab] = useState<"pairs" | "rooms">("pairs"); + + const load = useCallback(async () => { + setLoading(true); + setError(""); + try { + const data = (await fetchJson(`/api/youtube/assign/analytics/sources?days=${days}`)) as any; + setRecs(data.recommendations || []); + setRooms(data.rooms || []); + setWindowMeta(data.window || null); + } catch (e: any) { + setError(String(e?.message || e)); + } finally { + setLoading(false); + } + }, [days]); + + useEffect(() => { + void load(); + }, [load]); + + return ( + +
+
+
+
+
+ +
+
+
+ Fleet Scheduling Matrix +
+

抖音源 × YouTube 频道

+

+ 看清「哪个直播间」在「哪个频道」最好、该在什么北京时段开 — 用来安排 YouTube 直播选源与排班。 +

+ {windowMeta ? ( +

+ 近 {windowMeta.days} 天 · {windowMeta.room_count} 源 · {windowMeta.pair_count} 对关联 · {windowMeta.group_count} 频道 ·{" "} + {windowMeta.generated_at ? fmtTs(windowMeta.generated_at) : ""} +

+ ) : null} +
+
+
+ {[14, 30, 60].map((d) => ( + + ))} +
+ +
+
+ +
+ + +
+ + {error ?
{error}
: null} + {loading && !recs.length && !rooms.length ? ( +
+ 计算全站矩阵… +
+ ) : null} + + {tab === "pairs" ? ( +
+ {recs.map((r) => ( +
+
+
+ + #{r.rank} +
+
+

{r.anchor_name || r.room_id}

+ + live.douyin.com/{r.room_id} + + +
+
+
→
+
+
+ + {r.group_id ? ( + + {r.channel_name || "频道"} + + ) : ( + {r.channel_name} + )} + score {fmtNum(r.score)} +
+

{r.planning_tip}

+
+ 均 {fmtNum(r.avg_viewers)} + 峰 {fmtNum(r.peak_viewers)} + 总观 {fmtNum(r.max_total_views)} + {r.live_hours}h + {(r.best_hours || []).slice(0, 2).map((h, i) => ( + + {h.label} + + ))} +
+
+
+ ))} + {!recs.length && !loading ?

暂无配对数据

: null} +
+ ) : null} + + {tab === "rooms" ? ( +
+ {rooms.map((room) => ( +
+
+
+ +
+
+

{room.anchor_name || room.room_id}

+ + {room.room_id} + + {room.best_channel ? ( +

+ 最佳频道:{room.best_channel.channel_name}(score {fmtNum(room.best_channel.score)}) +

+ ) : null} +
+
+
+ {(room.channels || []).map((ch, i) => ( +
+ + {ch.channel_name || ch.group_id} + + + 均{fmtNum(ch.avg_viewers)} · 峰{fmtNum(ch.peak_viewers)} · {fmtNum(ch.score)} + +
+ ))} +
+
+ ))} + {!rooms.length && !loading ?

暂无源数据

: null} +
+ ) : null} +
+ + ); +} diff --git a/frontend/src/app/youtube/keys/page.tsx b/frontend/src/app/youtube/keys/page.tsx new file mode 100644 index 0000000..074cc65 --- /dev/null +++ b/frontend/src/app/youtube/keys/page.tsx @@ -0,0 +1,364 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { + ArrowLeft, + Copy, + Download, + KeyRound, + Loader2, + Plus, + RefreshCw, + Save, + Trash2, +} from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useToast } from "@/components/Toast"; +import { fetchJson } from "@/lib/api"; + +type KeyItem = { + id: string; + name?: string; + youtube_channel_id?: string; + channel_pk?: string; + assign_group_id?: string; + stream_key?: string; + stream_key_masked?: string; + has_stream_key?: boolean; + note?: string; + sort_order?: number; + updated_at?: number; +}; + +type Draft = { + id: string; + name: string; + youtube_channel_id: string; + channel_pk: string; + assign_group_id: string; + stream_key: string; + note: string; +}; + +const emptyDraft = (): Draft => ({ + id: "", + name: "", + youtube_channel_id: "", + channel_pk: "", + assign_group_id: "", + stream_key: "", + note: "", +}); + +export default function YoutubeStreamKeysPage() { + const toast = useToast(); + const confirm = useConfirm(); + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [draft, setDraft] = useState(emptyDraft()); + const [editingId, setEditingId] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const data = (await fetchJson("/api/youtube/stream-keys")) as { + items?: KeyItem[]; + }; + setItems(data.items || []); + } catch (e: any) { + toast.push(String(e?.message || e), "err"); + } finally { + setLoading(false); + } + }, [toast]); + + useEffect(() => { + void load(); + }, [load]); + + const startEdit = (it: KeyItem) => { + setEditingId(it.id); + setDraft({ + id: it.id, + name: it.name || "", + youtube_channel_id: it.youtube_channel_id || "", + channel_pk: it.channel_pk || "", + assign_group_id: it.assign_group_id || "", + stream_key: it.stream_key || "", + note: it.note || "", + }); + }; + + const startNew = () => { + setEditingId("__new__"); + setDraft(emptyDraft()); + }; + + const cancelEdit = () => { + setEditingId(null); + setDraft(emptyDraft()); + }; + + const save = async () => { + if (!draft.name.trim() && !draft.youtube_channel_id.trim()) { + toast.push("请填写频道名称或 YouTube Channel ID", "err"); + return; + } + setSaving(true); + try { + await fetchJson("/api/youtube/stream-keys", { + method: "POST", + body: JSON.stringify({ + id: draft.id || undefined, + name: draft.name, + youtube_channel_id: draft.youtube_channel_id, + channel_pk: draft.channel_pk, + assign_group_id: draft.assign_group_id, + stream_key: draft.stream_key, + note: draft.note, + }), + }); + toast.push("已保存到 Key 表(不影响推流/Neko)", "ok"); + cancelEdit(); + await load(); + } catch (e: any) { + toast.push(String(e?.message || e), "err"); + } finally { + setSaving(false); + } + }; + + const remove = async (id: string, name: string) => { + const ok = await confirm({ + title: "删除 Key 登记?", + message: `仅删除 Key 表中的「${name}」,不会改分配频道、不会动 Neko。`, + confirmLabel: "删除", + destructive: true, + }); + if (!ok) return; + try { + await fetchJson(`/api/youtube/stream-keys/${encodeURIComponent(id)}`, { method: "DELETE" }); + toast.push("已删除", "ok"); + await load(); + } catch (e: any) { + toast.push(String(e?.message || e), "err"); + } + }; + + const importAssign = async () => { + const ok = await confirm({ + title: "从分配频道导入?", + message: "把当前 /youtube 分配频道里的名称、UC、直播 Key 快照进本表。只写 Key 表,不改 Neko、不改推流状态。", + confirmLabel: "导入快照", + }); + if (!ok) return; + setSaving(true); + try { + const r = (await fetchJson("/api/youtube/stream-keys/import-assign", { + method: "POST", + body: JSON.stringify({ replace: false }), + })) as { inserted?: number; updated?: number; total?: number }; + toast.push(`导入完成:新增 ${r.inserted ?? 0} · 更新 ${r.updated ?? 0} · 共 ${r.total ?? 0}`, "ok"); + await load(); + } catch (e: any) { + toast.push(String(e?.message || e), "err"); + } finally { + setSaving(false); + } + }; + + const copyText = async (text: string, label: string) => { + try { + await navigator.clipboard.writeText(text); + toast.push(`已复制${label}`, "ok"); + } catch { + toast.push("复制失败", "err"); + } + }; + + return ( + +
+
+
+
+ + + 直播工作台 + + / + Key 表 +
+

+ + 频道 ↔ 直播 Key +

+

+ 独立登记表,用于找回对应关系。编辑本页不会启动/停止 Neko,也不会改正在推流的分配配置。 +

+
+
+ + + +
+
+ + {editingId ? ( +
+

+ {editingId === "__new__" ? "新建登记" : "编辑登记"} +

+
+ + + + + +
+
+ + +
+
+ ) : null} + + {loading ? ( +
+ + 加载中… +
+ ) : items.length === 0 ? ( +
+ 还没有登记。点「从分配导入」把当前直播 Key 快照进来,或点「新建」。 +
+ ) : ( +
+ {items.map((it) => { + const keyText = it.stream_key || it.stream_key_masked || ""; + return ( +
+
+
+
{it.name || "未命名"}
+
+ {it.youtube_channel_id || "—"} +
+ {it.note ?
{it.note}
: null} +
+
+ + + +
+
+
{keyText || "—"}
+
+ ); + })} +
+ )} +
+
+ ); +} diff --git a/frontend/src/app/youtube/page.tsx b/frontend/src/app/youtube/page.tsx index b61cb27..db07fb5 100644 --- a/frontend/src/app/youtube/page.tsx +++ b/frontend/src/app/youtube/page.tsx @@ -78,7 +78,6 @@ export default function YouTubePage() { const [videos, setVideos] = useState([]); const [playlists, setPlaylists] = useState([]); const [edit, setEdit] = useState(null); - const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [msg, setMsg] = useState(""); @@ -102,7 +101,6 @@ export default function YouTubePage() { const loadManage = useCallback(async () => { if (!channelPk) return; - setBusy(true); setError(""); try { const [d, v, p] = await Promise.all([ @@ -117,8 +115,6 @@ export default function YouTubePage() { setError((e as Error).message); setDash(null); setVideos([]); - } finally { - setBusy(false); } }, [channelPk]); @@ -146,7 +142,6 @@ export default function YouTubePage() { async function saveVideo() { if (!edit || !channelPk) return; - setBusy(true); setError(""); setMsg(""); try { @@ -165,14 +160,11 @@ export default function YouTubePage() { await loadManage(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } async function setPrivacy(videoId: string, privacy: string) { if (!channelPk) return; - setBusy(true); try { await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "PATCH", @@ -182,8 +174,6 @@ export default function YouTubePage() { await loadManage(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -196,7 +186,6 @@ export default function YouTubePage() { destructive: true, }); if (!ok) return; - setBusy(true); try { await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" }); toast.push("视频已删除", "ok"); @@ -204,8 +193,6 @@ export default function YouTubePage() { } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } @@ -218,7 +205,6 @@ export default function YouTubePage() { } async function runProbe() { - setBusy(true); setError(""); setMsg(""); setResult(null); @@ -233,8 +219,6 @@ export default function YouTubePage() { setResult(data); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -391,7 +375,7 @@ export default function YouTubePage() { onClick={() => void loadManage()} className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm" > - {busy ? : } + 刷新
@@ -588,7 +572,6 @@ export default function YouTubePage() {
diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index 0ac089a..9989b25 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -191,7 +191,6 @@ export default function YtLongPage() { const [upcoming, setUpcoming] = useState([]); const [form, setForm] = useState({ ...emptyForm }); const [editId, setEditId] = useState(""); - const [busy, setBusy] = useState(false); const [togglingId, setTogglingId] = useState(""); const [msg, setMsg] = useState(""); const [error, setError] = useState(""); @@ -203,10 +202,11 @@ export default function YtLongPage() { const [loadingMoreJobs, setLoadingMoreJobs] = useState(false); const load = useCallback( - async (opts?: { appendJobs?: boolean; jobOffset?: number }) => { + async (opts?: { appendJobs?: boolean; jobOffset?: number; soft?: boolean }) => { const appendJobs = Boolean(opts?.appendJobs); + const soft = Boolean(opts?.soft); if (appendJobs) setLoadingMoreJobs(true); - else setLoading(true); + else if (!soft) setLoading(true); try { const off = appendJobs ? Number(opts?.jobOffset ?? 0) : 0; const jobQs = new URLSearchParams({ limit: String(JOB_PAGE), offset: String(off) }); @@ -381,16 +381,16 @@ export default function YtLongPage() { const totals = useMemo(() => { const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0); - const used = displayChannels.reduce((s, c) => s + (c.used || 0), 0); + // Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。 + const used = uploaded; const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0); const gap = displayChannels .filter((c) => c.enabled !== false) - .reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 0) - (c.used || 0))), 0); + .reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0); return { uploaded, scheduled, used, cap, gap }; }, [displayChannels]); async function toggle(enabled: boolean) { - setBusy(true); setMsg(""); setError(""); try { @@ -399,13 +399,10 @@ export default function YtLongPage() { await load(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } async function importFromShorts() { - setBusy(true); setMsg(""); setError(""); try { @@ -416,13 +413,10 @@ export default function YtLongPage() { } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); - } finally { - setBusy(false); } } async function saveChannel() { - setBusy(true); setMsg(""); setError(""); try { @@ -449,8 +443,6 @@ export default function YtLongPage() { await load(); } catch (e) { setError((e as Error).message); - } finally { - setBusy(false); } } @@ -505,7 +497,10 @@ export default function YtLongPage() { } else { toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok"); } - await load(); + setChannels((prev) => + prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)), + ); + await load({ soft: true }); } catch (e) { toast.push((e as Error).message, "err"); } finally { @@ -551,8 +546,8 @@ export default function YtLongPage() { {[ [ "YouTube 上传", - `${status?.upload_used ?? status?.quota_used ?? 0} / ${status?.daily_max ?? "—"}`, - beijingWindow ? `${beijingWindow} · 长视频上传上限` : "长视频上传日上限(14×3)", + `${totals.uploaded} / ${totals.cap || status?.daily_max || "—"}`, + beijingWindow ? `${beijingWindow} · 已上传 / 各频道日上限合计` : "进度按已上传(不含排队占坑)", ], [ "母片录制", @@ -568,16 +563,24 @@ export default function YtLongPage() { [ "成片规格", `${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`, - "9:16 竖屏 · cascade 切短片", + status?.api_quota_limited + ? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}` + : "9:16 竖屏 · cascade 切短片", ], - ].map(([label, value, hint]) => ( -
-
{label}
-
{value}
-
{hint}
+ ].map(([title, value, sub]) => ( +
+

{title}

+

{value}

+

{sub}

))}
+ {status?.api_quota_limited ? ( +
+ YouTube 上传接口今日限流(429)。长视频每频道上限已软降为{" "} + {status?.channel_daily_max_effective ?? 4};Shorts/长视频自动上传对冷静中的 Client 会跳过,手动上传不拦。 +
+ ) : null} { @@ -624,7 +627,6 @@ export default function YtLongPage() { 开关
{group.channels.map((ch) => { - const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100)); + // 进度条只按「已上传」,与 /shorts 一致;排队占坑不算进度。 + const progress = Number(ch.uploaded ?? 0); + const pct = Math.min(100, Math.round((progress / Math.max(1, ch.daily_max)) * 100)); const full = channels.find((x) => x.id === ch.id); - const gap = ch.gap ?? Math.max(0, ch.daily_max - ch.used); + const gap = Math.max(0, (ch.daily_max || 0) - progress); return (
- {ch.used}/{ch.daily_max || 0} + 上传 {progress}/{ch.daily_max || 0} {gap > 0 ? ( 缺 {gap} ) : ( 已满 )} - 上传 {ch.uploaded} 排队 {ch.scheduled} 待录 {ch.pending}
@@ -969,11 +964,10 @@ export default function YtLongPage() {

- 普通 = 手动推流(精选源);时间段 = 24/N 排班 + 在播抖音源。其他分类待定。 + 普通 = 关「时间段排班」且开「自动推流」时监听直播地址列表;时间段 = 24/N + 监控在播抖音。单路独占时只跑最先开播的那一路。

{channels.length === 0 ? (

@@ -1560,91 +1570,241 @@ export function YtAssignPanel({

) : ( <> - {slotConflicts.length > 0 ? ( -
-
时段冲突:同一 Douyin URL 被分配到多个频道时段
-
    - {slotConflicts.slice(0, 6).map((c) => ( -
  • - {c.channels.join(" · ")} — {(c.url || c.key).slice(0, 48)} -
  • - ))} -
+ {timeSlotModeOn ? ( + <> + {slotConflicts.length > 0 ? ( +
+
时段冲突:同一 Douyin URL 被分配到多个频道时段
+
    + {slotConflicts.slice(0, 6).map((c) => ( +
  • + {c.channels.join(" · ")} — {(c.url || c.key).slice(0, 48)} +
  • + ))} +
+
+ ) : null} + {schedule && (schedule.channels || []).length > 0 ? ( +
+
+
+

+ 时间段排班 ·「时间段」分类频道(北京时间) +

+

+ {schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "} + {schedule.now_label} · 源=在播抖音 +

+
+
+ +
+
+
+ {(schedule.channels || []).map((ch) => { + const active = Boolean(ch.active); + const selectedNow = ch.group_id === groupId; + return ( + + ); + })} +
+
+ ) : ( +
+ 时间段排班已开,但还没有带 KEY 的「时间段」分类频道 +
+ )} + + ) : ( +
+
+
+
+

普通频道 · 在播抖音

+

+ 来自各普通频道「直播地址列表」· 与首页同款在播态势 + {Boolean(relayStatus?.enabled) + ? " · 开播即自动推流" + : " · 自动推流关时可先观察"} +

+
+ + {normalLiveRooms.length} 路在播 + +
+ {normalLiveRooms.length === 0 ? ( +
+ 当前没有普通频道直播地址在播 +
+ ) : ( +
+ {normalLiveRooms.map((row) => ( + + ))} +
+ )} +
+ +
+
+
+

普通频道

+

+ {normalGroups.length} 个 · 动效标出当前在播 / 推流 + {exclusiveLiveOn && exclusiveWinnerName + ? ` · 独占中 ${exclusiveWinnerName}` + : ""} +

+
+
+ {normalGroups.length === 0 ? ( +
+ 还没有普通分类分组 +
+ ) : ( +
+ {normalGroups.map((g) => { + const pk = String(g.channel_pk || ""); + const monitor = relayEntries.find((e) => e.group_id === g.id); + const pushing = isLivePushingRow(monitor); + const ytLive = liveAssignIds.has(g.id); + const onAir = pushing || ytLive; + const winner = exclusiveWinnerId === g.id; + const selectedNow = g.id === groupId; + const liveFeatCount = normalLiveRooms.filter((r) => r.groupId === g.id).length; + return ( + + ); + })} +
+ )} +
- ) : null} - {schedule && (schedule.channels || []).length > 0 ? ( -
-
-
-

- {timeSlotModeOn || schedule.time_slot_mode - ? "时间段排班 ·「时间段」分类频道(北京时间)" - : "24 小时频道轮播(北京时间)"} -

-

- {schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "} - {schedule.now_label} - {timeSlotModeOn || schedule.time_slot_mode ? " · 源=在播抖音" : ""} -

-
-
- - -
-
-
- {(schedule.channels || []).map((ch) => { - const active = Boolean(ch.active); - const selectedNow = ch.group_id === groupId; - return ( - - ); - })} -
-
- ) : null} + )}
-
-
+
+

普通列表(URL 池)· {(selected.pool || []).length} @@ -2001,7 +2162,6 @@ export function YtAssignPanel({ ) : ( (selected.pool || []).map((u) => { const inFeat = featuredIds.has(u.id); - const inSlot = slotIds.has(u.id); const banned = Boolean(u.blacklisted); return (
-

-
-
-

- 时间段列表(轮播)· {(selected.slots || []).length} -

-
- - - -
-
-

- 本频道 {selectedSchedule?.start_label || "—"}–{selectedSchedule?.end_label || "—"} 内按序轮播抖音源;多频道错开时段,避免同时推流。 -

-
- {(selected.slots || []).length === 0 ? ( -
- 从普通列表点时钟图标加入,或点「填充直播」 -
- ) : ( - (selected.slots || []).map((s, i) => { - const banned = Boolean(s.blacklisted); - const inFeat = s.pool_url_id ? featuredIds.has(s.pool_url_id) : false; - const schSlot = (schedule?.channels || []) - .find((c) => c.group_id === selected.id) - ?.slots?.[i] as SlotUrl | undefined; - const timeLabel = - schSlot?.window_start_label && schSlot?.window_end_label - ? `${schSlot.window_start_label}–${schSlot.window_end_label}` - : null; - return ( -
- - #{i + 1} - - - setLightbox({ src, title: s.title || "封面", subtitle: s.url }) - } - /> -
-
-
{displayAnchor(s)}
- {s.room_id ? : null} - {timeLabel ? ( - - {timeLabel} - - ) : null} - {banned ? ( - - 黑名单 - - ) : null} -
- - {s.url || s.pool_url_id} - -
-
- {s.pool_url_id ? ( - - ) : null} - {s.pool_url_id ? ( - - ) : null} - -
-
- ); - }) - )} -
-
- -
+

直播地址列表 · {(selected.featured || []).length} @@ -2258,12 +2266,12 @@ export function YtAssignPanel({

- 即分配页的精选列表;FFmpeg 推流只从此列表选源(优先在播)。从普通池点 ★ 加入。 + 关「时间段排班」且开「自动推流」时:从此列表监听开播并推流(优先在播)。单路独占时只跑最先开播的频道。从普通池点 ★ 加入。

{(selected.featured || []).length === 0 ? (
- 从左侧普通列表点星标加入精选 + 从左侧普通列表点星标加入
) : ( (selected.featured || []).map((f, i) => { @@ -2357,7 +2365,7 @@ export function YtAssignPanel({

排除手动直播名单

- 不是黑名单:这些抖音间仍可监控 / 手动推流。时间段自动选源与「全频道填充」不会选用它们,避免与已指定的手动直播撞同一路流。 + 不是黑名单:这些抖音间仍可监控 / 手动推流。时间段自动选源不会选用它们,避免与已指定的手动直播撞同一路流。

diff --git a/frontend/src/components/YtRelayProStatusPanel.tsx b/frontend/src/components/YtRelayProStatusPanel.tsx index f19e5a3..edc33df 100644 --- a/frontend/src/components/YtRelayProStatusPanel.tsx +++ b/frontend/src/components/YtRelayProStatusPanel.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { useCallback, useEffect, useState } from "react"; -import { ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react"; +import { Copy, ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react"; import { DouyinLiveBadge } from "@/components/DouyinLiveBadge"; import { EnableSwitch } from "@/components/EnableSwitch"; @@ -29,6 +29,7 @@ type GroupLike = { name?: string; enabled?: boolean; has_stream_key?: boolean; + stream_key?: string; featured?: Array<{ url?: string }>; neko_instance_id?: number; neko_enabled?: boolean; @@ -131,6 +132,8 @@ export function YtRelayProStatusPanel({ const douyinSubtitle = row?.source_display || row?.source_title || ""; const dUrl = row?.source_url || ""; const suf = row?.stream_key_suffix || "—"; + const fullKey = String(group.stream_key || row?.stream_key || "").trim(); + const keyLabel = fullKey || (suf && suf !== "—" ? `…${suf}` : ""); const urlCount = row?.url_count ?? (group.featured || []).length; const dyCount = row?.douyin_count ?? urlCount; const blocked = procStartBlocked(row); @@ -150,6 +153,10 @@ export function YtRelayProStatusPanel({ const [openPrefer, setOpenPrefer] = useState<"local" | "remote">( group.neko_open_prefer === "remote" ? "remote" : "local", ); + // Exclusive / time-slot may leave the container running while DB neko_enabled=0. + // Power switch must follow container reality (except while a local toggle is in-flight). + const containerOn = Boolean(nekoState?.running || nekoState?.ready); + const nekoPowerOn = nekoBusy ? nekoEnabled : Boolean(nekoEnabled || containerOn); const localStudioUrl = String( group.neko_local_studio_url || group.neko_studio_url || nekoState?.studio_url || "", ).trim(); @@ -161,20 +168,24 @@ export function YtRelayProStatusPanel({ : localStudioUrl || String(nekoState?.studio_url || "").trim(); useEffect(() => { + if (nekoBusy) return; // avoid overwriting optimistic power flip mid-flight setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled)); - }, [group.id, group.neko_enabled, row?.neko_enabled]); + }, [group.id, group.neko_enabled, row?.neko_enabled, nekoBusy]); useEffect(() => { + if (nekoBusy) return; setOpenPrefer(group.neko_open_prefer === "remote" ? "remote" : "local"); - }, [group.id, group.neko_open_prefer]); + }, [group.id, group.neko_open_prefer, nekoBusy]); // Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop. useEffect(() => { + if (nekoBusy) return; if (row?.neko) { setNekoState(row.neko as NekoState); setNekoPollErr(""); } }, [ + nekoBusy, row?.neko, row?.neko?.status, row?.neko?.ready, @@ -215,6 +226,25 @@ export function YtRelayProStatusPanel({ }, [instanceId, row?.neko, refreshNeko]); async function postNeko(body: Record) { + const wantOn = + typeof body.enabled === "boolean" + ? Boolean(body.enabled) + : String(body.action || "") === "start"; + // Optimistic: flip switch immediately — never wait on docker + full panel reload. + setNekoEnabled(wantOn); + if (!wantOn) { + setNekoState((prev) => + prev + ? { ...prev, running: false, ready: false, status: "exited" } + : prev, + ); + } else { + setNekoState((prev) => + prev + ? { ...prev, running: true, ready: Boolean(prev.ready), status: prev.ready ? "healthy" : "starting" } + : { running: true, ready: false, status: "starting" }, + ); + } setNekoBusy(true); try { const r = (await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko`, { @@ -222,11 +252,20 @@ export function YtRelayProStatusPanel({ body: JSON.stringify(body), })) as { group?: GroupLike; neko?: NekoState }; if (r.group) setNekoEnabled(Boolean(r.group.neko_enabled)); - if (r.neko) setNekoState(r.neko); + if (r.neko) { + setNekoState((prev) => ({ + ...r.neko!, + studio: (r.neko as NekoState)?.studio ?? prev?.studio ?? null, + })); + } + // Parent must silent-refresh — never setBusy on whole assign panel. onNekoChange?.(); - await refreshNeko(); } catch (e) { + // Roll back optimistic power state from last known server bits. + setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled)); + if (row?.neko) setNekoState(row.neko as NekoState); toast.push((e as Error).message, "err"); + void refreshNeko(); } finally { setNekoBusy(false); } @@ -234,7 +273,7 @@ export function YtRelayProStatusPanel({ async function setPrefer(prefer: "local" | "remote") { if (prefer === "remote" && !remoteBound) { - toast.push("请先在下方下拉框选择物理机 ops-neko 实例", "err"); + toast.push("请先在下方下拉框选择远程 ops-neko 实例", "err"); return; } setNekoBusy(true); @@ -274,7 +313,7 @@ export function YtRelayProStatusPanel({ return; } const item = remoteCatalog.find((x) => String(x.id || `${x.edge_id}:${x.slot}`) === catalogId); - if (!item?.open_url) throw new Error("未找到该物理机实例"); + if (!item?.open_url) throw new Error("未找到该远程实例"); const r = (await fetchJson( `/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`, { @@ -355,7 +394,26 @@ export function YtRelayProStatusPanel({ · ) : null} - key …{suf} + + + key {keyLabel || "—"} + + {fullKey ? ( + + ) : null} + · URL {urlCount} · @@ -385,6 +443,14 @@ export function YtRelayProStatusPanel({
+ + 数据 +
void postNeko({ enabled: v, action: v ? "start" : "stop" })} />

- 本机原生 Neko #{instanceId} 始终保留(默认停止)。密码{" "} + 本机 Neko #{instanceId}:启用=启动容器,关闭=停止(新建默认关)。密码{" "} douyinweb - 。地址须带尾斜杠。 + 。开关跟随容器实态 + {containerOn && !nekoEnabled && !nekoBusy ? ( + (容器在跑,DB 未启用 — 已按运行显示) + ) : null} + 。 {nekoPollErr ? ({nekoPollErr}) : null}

- {/* Remote Neko — always visible UX (paired or empty CTA) */} + {/* Remote Neko — prefer + bind */}
@@ -483,18 +555,20 @@ export function YtRelayProStatusPanel({ ? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${ group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : "" }` - : "选择物理机 ops-neko,或先完成 Neko 页配对同步目录"} + : "未绑定:可选远程实例;双 VPS 通常只用本机 Neko"}

- - 打开 Neko Tab - + {!remoteBound ? ( + + 去配对 + + ) : null}
- 默认打开 + 打开偏好
{showRemotePicker ? ( ) : null}
-
+
{preferredUrl ? ( - 打开工作室 + {pushing && !(nekoState?.studio?.live_page_open) + ? "打开 Live 控制页" + : "打开工作室"} {openPrefer === "remote" && remoteBound ? "(远程)" : "(本机)"} ) : null} - {localStudioUrl ? ( + {openPrefer === "remote" && remoteBound && localStudioUrl ? ( - 本机原生 + 另开本机 ) : null} - {remoteStudioUrl ? ( + {openPrefer === "local" && remoteStudioUrl ? ( - 远程 Neko + 另开远程 - ) : ( - void postNeko({ action: "restart" })} + className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40" + title="重启本机 Docker Neko(不影响远程)" > - 去配对远程… - - )} - - - + + 重启本机 + + ) : null}
{(() => { const st = nekoState?.studio; const preferRemote = openPrefer === "remote" && remoteBound; - // Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred. - if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote) return null; + // Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred + // OR YouTube is already receiving (FFmpeg push) — receiving-first. + const ytReceiving = isLivePushingRow(row); + if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote && !ytReceiving) return null; const reports = st?.minute_reports || []; + const studioOnAir = Boolean(st?.on_air); + const livePageOpen = Boolean(st?.live_page_open); const viewers = st?.viewer_count != null && Number.isFinite(Number(st.viewer_count)) ? Number(st.viewer_count).toLocaleString() @@ -644,7 +705,16 @@ export function YtRelayProStatusPanel({ ? "本机 Neko 数据" : preferRemote ? "远程(等待同步)" - : "本机"; + : ytReceiving && !st + ? "接流优先" + : "本机"; + // Receiving-first: never imply channel offline when YouTube ingest / FFmpeg is live. + const airLabel = studioOnAir + ? "Studio 开播中" + : ytReceiving + ? "YouTube 接流中" + : "Studio 未开播"; + const airHot = studioOnAir || ytReceiving; return (
@@ -658,6 +728,14 @@ export function YtRelayProStatusPanel({ > {srcLabel} + {ytReceiving ? ( + + 推流接流 + + ) : null} {st?.live_status === "signed_out" ? ( Google 已登出 — 请打开工作室点选账号重新登录 @@ -665,28 +743,29 @@ export function YtRelayProStatusPanel({ ) : null} - Live 页 {st?.live_page_open ? "已打开" : "未打开"} + Live 页 {livePageOpen ? "已打开" : "未打开"} - {st?.on_air ? "开播中" : "未开播"} + {airLabel} - {st?.on_air || liveDur !== "—" ? ( + {studioOnAir || liveDur !== "—" ? ( LIVE {liveDur} ) : null} - {st?.live_status ? ( + {st?.live_status && st.live_status !== "signed_out" ? ( {st.live_status} @@ -706,6 +785,14 @@ export function YtRelayProStatusPanel({ {Math.round(Number(st.age_sec))}s 前 ) : null}
+ {ytReceiving && !livePageOpen ? ( +

+ YouTube 已在接流;当前刮数源未见 Studio Live 页(观看数为 —)。 + {remoteBound + ? "若 Live 开在远程 Neko,请把「打开偏好」切到远程,或点「另开远程」进 Live 控制页。" + : "点「打开 Live 控制页」进入本机 Studio Live 即可刮数。"} +

+ ) : null} {st?.stream_title ? (

{st.stream_title} @@ -717,13 +804,15 @@ export function YtRelayProStatusPanel({ currentViewers={st?.viewer_count} currentTotalViews={st?.total_views} currentDuration={st?.live_duration} - onAir={Boolean(st?.on_air)} + onAir={studioOnAir || ytReceiving} /> ) : (

- {preferRemote - ? "远程分钟报告同步中(物理机开播约 1 分钟后出现;每 5 秒经目录同步到 VPS)" - : "暂无分钟报告(开播后约 1 分钟开始汇总)"} + {ytReceiving && !livePageOpen + ? "接流中但 Live 页未开,暂无分钟报告 — 打开工作室 Live 页约 1 分钟后开始汇总" + : preferRemote + ? "远程分钟报告同步中(对端开播约 1 分钟后出现;每 5 秒经目录同步)" + : "暂无分钟报告(Studio 开播后约 1 分钟开始汇总)"}

)}
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index d0af2e1..898d037 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -4,18 +4,55 @@ export function clearAuthRedirect() { } } +/** + * JSON fetch with credentials + default timeout. + * @param {string} url + * @param {RequestInit & { timeoutMs?: number }} [init] + */ export async function fetchJson(url, init) { const apiKey = typeof window !== "undefined" ? window.localStorage.getItem("dy_api_key") || "" : ""; - const res = await fetch(url, { - ...init, - credentials: "include", - headers: { - "Content-Type": "application/json", - ...(apiKey ? { "X-API-Key": apiKey } : {}), - ...(init?.headers || {}), - }, - }); + const timeoutMs = Number(init?.timeoutMs); + const ms = + Number.isFinite(timeoutMs) && timeoutMs > 0 + ? timeoutMs + : /\/(upload|avatar|sync|import|export|backup)/i.test(String(url)) + ? 60000 + : 15000; + const { timeoutMs: _drop, ...fetchInit } = init || {}; + const ac = new AbortController(); + const userSignal = fetchInit.signal; + let onUserAbort = null; + if (userSignal) { + if (userSignal.aborted) ac.abort(); + else { + onUserAbort = () => ac.abort(); + userSignal.addEventListener("abort", onUserAbort, { once: true }); + } + } + const timer = setTimeout(() => ac.abort(), ms); + let res; + try { + res = await fetch(url, { + ...fetchInit, + signal: ac.signal, + credentials: "include", + headers: { + "Content-Type": "application/json", + ...(apiKey ? { "X-API-Key": apiKey } : {}), + ...(fetchInit.headers || {}), + }, + }); + } catch (e) { + const name = e && e.name; + if (name === "AbortError") { + throw new Error(`请求超时(${Math.round(ms / 1000)}s),请稍后重试`); + } + throw e; + } finally { + clearTimeout(timer); + if (userSignal && onUserAbort) userSignal.removeEventListener("abort", onUserAbort); + } const text = await res.text(); let data = null; try { @@ -145,22 +182,30 @@ export function fmtClock(ts) { } } -/** Prefer channel avatar, then public S3 cover, then API proxy. */ +/** Prefer channel avatar (trusted public S3), then cover, then API proxy. */ export function sessionCoverSrc(session, bust = true) { if (!session) return ""; const avatarUrl = String(session.avatar_url || "").trim(); const publicUrl = String(session.cover_url || "").trim(); const proxyUrl = String(session.cover_proxy_url || "").trim(); const fallback = session.id ? `/api/sessions/${session.id}/cover` : ""; + // Only trust avatar hosts that serve anonymous public objects. Broken dual-edge + // hosts (dy.nomadro.com FRP) previously blanked the whole card. + const avatarOk = + /^https:\/\/s3\.nomadro\.com\//i.test(avatarUrl) || + /^https:\/\/dy\.nomadro\.live\/douyin-covers\//i.test(avatarUrl); + const httpOk = (u) => + /^(https?:)\/\//i.test(u) && + !/^https?:\/\/dy\.nomadro\.com\/douyin-covers\//i.test(u); // Channel avatar (S3) first — stream-frame covers are not profile faces. const base = - (avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://") ? avatarUrl : "") || - (publicUrl.startsWith("http://") || publicUrl.startsWith("https://") ? publicUrl : "") || - (proxyUrl.startsWith("http://") || proxyUrl.startsWith("https://") ? proxyUrl : "") || + (avatarOk ? avatarUrl : "") || + (httpOk(publicUrl) ? publicUrl : "") || + (httpOk(proxyUrl) ? proxyUrl : "") || proxyUrl || fallback || publicUrl || - avatarUrl || + (avatarOk ? avatarUrl : "") || ""; if (!base) return ""; if (!bust) return base; diff --git a/frontend/src/lib/douyinLive.ts b/frontend/src/lib/douyinLive.ts index dbb8505..a7a85e8 100644 --- a/frontend/src/lib/douyinLive.ts +++ b/frontend/src/lib/douyinLive.ts @@ -33,12 +33,15 @@ const DouyinLiveContext = createContext<{ refresh: async () => {}, }); -export function useDouyinLiveProviderValue(intervalMs = 25000) { +export function useDouyinLiveProviderValue(intervalMs = 35000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); const { tick, last } = useEventStream(true); + const inFlight = useMemo(() => ({ current: false }), []); const refresh = useCallback(async (silent = false) => { + if (inFlight.current) return; + inFlight.current = true; if (!silent) setLoading(true); try { const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap; @@ -46,9 +49,10 @@ export function useDouyinLiveProviderValue(intervalMs = 25000) { } catch { /* keep last map */ } finally { + inFlight.current = false; if (!silent) setLoading(false); } - }, []); + }, [inFlight]); useEffect(() => { void refresh(true); diff --git a/frontend/src/lib/youtubeLive.ts b/frontend/src/lib/youtubeLive.ts index 87d11c2..0520989 100644 --- a/frontend/src/lib/youtubeLive.ts +++ b/frontend/src/lib/youtubeLive.ts @@ -49,8 +49,11 @@ export function channelLiveRef(channelId: string) { export function useYouTubeLiveProviderValue(intervalMs = 35000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); + const inFlight = useMemo(() => ({ current: false }), []); const refresh = useCallback(async (silent = false) => { + if (inFlight.current) return; + inFlight.current = true; if (!silent) setLoading(true); try { // 不 force:读服务端后台轮询写入的缓存(约 15–20s 更新) @@ -59,9 +62,10 @@ export function useYouTubeLiveProviderValue(intervalMs = 35000) { } catch { /* keep last map */ } finally { + inFlight.current = false; if (!silent) setLoading(false); } - }, []); + }, [inFlight]); useEffect(() => { void refresh(true); diff --git a/frontend/src/lib/ytRelayStatus.ts b/frontend/src/lib/ytRelayStatus.ts index c1e8abd..a1c834f 100644 --- a/frontend/src/lib/ytRelayStatus.ts +++ b/frontend/src/lib/ytRelayStatus.ts @@ -26,6 +26,7 @@ export type RelayMonitorRow = { url_count?: number; douyin_count?: number; has_stream_key?: boolean; + stream_key?: string; stream_key_suffix?: string; neko_instance_id?: number; neko_enabled?: boolean; @@ -84,6 +85,8 @@ export function businessStatusLabel(row?: RelayMonitorRow): string { if (business === "source_live") return "源已开播"; if (business === "monitoring") return "监听中"; if (business === "outside_slot") return "时段外"; + if (business === "paused_exclusive") return "独占暂停"; + if (business === "paused_studio") return "Studio熔断"; if (business === "misconfigured") return "密钥异常"; if (business === "youtube_key_rejected") return "密钥被拒"; if (business === "stale") return "心跳过期"; @@ -103,6 +106,9 @@ export function businessStatusBadgeClass(row?: RelayMonitorRow): string { if (business === "waiting_source" || business === "monitoring" || business === "relay_starting" || business === "outside_slot") { return "bg-amber-500/15 text-amber-100 ring-amber-500/25"; } + if (business === "paused_exclusive" || business === "paused_studio") { + return "bg-amber-500/15 text-amber-100 ring-amber-500/25"; + } if (business === "source_live") return "bg-sky-500/15 text-sky-100 ring-sky-500/25"; if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") { return "bg-rose-500/15 text-rose-100 ring-rose-500/25"; diff --git a/scripts/_align_assign_neko_tm_both.py b/scripts/_align_assign_neko_tm_both.py new file mode 100644 index 0000000..bffca40 --- /dev/null +++ b/scripts/_align_assign_neko_tm_both.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Align assign-neko TM on PHYSICAL + VPS: offline load-extension, never touch Secure Preferences.""" +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +FILES = { + "browser-launch.sh": ROOT / "backend/neko/browser-launch.sh", + "policies.json": ROOT / "backend/neko/policies/policies.json", + "Preferences": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences", + "manifest.json": ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json", +} + +# Seed TM into profile only (Preferences + Extensions). NEVER Secure Preferences / Cookies. +SEED_PROFILE = r''' +import json, shutil +from pathlib import Path +EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE=Path("/home/neko/.config/google-chrome/Default") +SEED=Path("/etc/neko/tampermonkey-seed/Default") +SEED_EXT=SEED/"Extensions"/EXT +SEED_PREF=SEED/"Preferences" + +def load(p): + try: return json.loads(p.read_text(encoding="utf-8")) + except Exception: return {} + +if not SEED_EXT.exists(): + raise SystemExit("NO_SEED_EXT") +# copy extension files if missing or empty +dst=BASE/"Extensions"/EXT +if dst.exists(): + shutil.rmtree(dst, ignore_errors=True) +(BASE/"Extensions").mkdir(parents=True, exist_ok=True) +shutil.copytree(SEED_EXT, dst) +# strip update_url +mf=dst/"5.5.0_0"/"manifest.json" +if mf.exists(): + md=load(mf); md.pop("update_url", None) + mf.write_text(json.dumps(md, ensure_ascii=False, indent=3)+"\n", encoding="utf-8") +# Preferences only — NEVER Secure Preferences +seed_entry=((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) or {} +entry=dict(seed_entry) if isinstance(seed_entry, dict) else {} +entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False}) +entry.pop("disable_reasons", None) +mf2=entry.get("manifest") +if isinstance(mf2, dict): + mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2 +pref=BASE/"Preferences" +d=load(pref) if pref.exists() else {} +d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry) +d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True +pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8") +print("seeded_tm_ok") +''' + +REMOTE_SH = r''' +set -e +ROOT=/opt/douyinWEB/backend/neko +# in-place overwrite (preserve bind-mount inodes) +cat /tmp/browser-launch.sh.tmfix > "$ROOT/browser-launch.sh" +chmod 755 "$ROOT/browser-launch.sh" +cat /tmp/policies.json.tmfix > "$ROOT/policies/policies.json" +chmod 644 "$ROOT/policies/policies.json" +cat /tmp/Preferences.tmfix > "$ROOT/tampermonkey-seed/Default/Preferences" +chmod 644 "$ROOT/tampermonkey-seed/Default/Preferences" +MF="$ROOT/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" +if [ -f "$MF" ]; then cat /tmp/manifest.json.tmfix > "$MF"; chmod 644 "$MF"; fi + +# ensure chromium policy dirs also get same file if separate mounts exist on host +for d in /etc/opt/chrome/policies/managed /etc/chromium/policies/managed /etc/chromium-browser/policies/managed; do + if [ -d "$d" ] || [ -L "$d" ]; then + mkdir -p "$d" 2>/dev/null || true + fi +done + +echo "=== remount check browser-launch ===" +# force container remount of host files by stop/start running assign nekos +NAMES=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort || true) +echo "running: $NAMES" +for name in $NAMES; do + echo "===== SEED $name =====" + docker exec -i "$name" tee /tmp/_seed_tm.py < /tmp/_seed_tm_profile.py >/dev/null + docker exec "$name" python3 /tmp/_seed_tm.py || echo SEED_FAIL + # verify policy mount + docker exec "$name" bash -lc 'ls -la /etc/opt/chrome/policies/managed/policies.json 2>/dev/null || echo NO_POLICY_MOUNT; grep -n Offline /etc/neko/browser-launch.sh | head -3 || echo NO_OFFLINE_IN_LAUNCH' + docker exec "$name" supervisorctl restart google-chrome || docker exec "$name" supervisorctl start google-chrome || true +done +# if none running, still update host assets; operator starts manually +sleep 12 +for name in $NAMES; do + echo "===== VERIFY $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, os, re, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +e=((json.loads(Path("/home/neko/.config/google-chrome/Default/Preferences").read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("tm", e.get("state"), e.get("location"), e.get("from_webstore"), "path", e.get("path")) +print("ext", Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0/manifest.json").exists()) +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00",b" ").decode() + except Exception: continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_ext", m.group(1) if m else None); found=True; break +if not found: print("load_ext NONE") +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +except Exception as ex: + print("cdp", ex); tabs=[] +print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or ""))) +PY +done +''' + + +def do_host(label: str, host: str, port: int, user: str, pw: str, use_sudo: bool) -> None: + print(f"\n########## {label} ##########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for name, path in FILES.items(): + with sftp.file(f"/tmp/{name}.tmfix", "wb") as f: + f.write(path.read_bytes()) + print("up", name, flush=True) + with sftp.file("/tmp/_seed_tm_profile.py", "wb") as f: + f.write(SEED_PROFILE.encode()) + with sftp.file("/tmp/_align_tm_remote.sh", "wb") as f: + f.write(REMOTE_SH.encode()) + sftp.close() + if use_sudo: + cmd = f"echo {pw} | sudo -S -p '' bash /tmp/_align_tm_remote.sh" + else: + cmd = "bash /tmp/_align_tm_remote.sh" + _i, o, e = c.exec_command(cmd, timeout=420) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +def main() -> None: + # Ensure local seed prefs/manifest are offline + pref = FILES["Preferences"] + import json + + d = json.loads(pref.read_text(encoding="utf-8")) + e = d["extensions"]["settings"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"] + e["location"] = 4 + e["from_webstore"] = False + if isinstance(e.get("manifest"), dict): + e["manifest"].pop("update_url", None) + pref.write_text(json.dumps(d, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + mf = FILES["manifest.json"] + md = json.loads(mf.read_text(encoding="utf-8")) + md.pop("update_url", None) + mf.write_text(json.dumps(md, ensure_ascii=False, indent=3) + "\n", encoding="utf-8") + + do_host("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True) + do_host("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) + + +if __name__ == "__main__": + main() diff --git a/scripts/_apply_neko_oom_protect.py b/scripts/_apply_neko_oom_protect.py new file mode 100644 index 0000000..f3bca17 --- /dev/null +++ b/scripts/_apply_neko_oom_protect.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Apply host-level OOM protection to neko-7 processes + hard-restart Chrome with new flags.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +c = ssh() +run( + c, + r""" +set -euo pipefail + +# Persist helper: protect all PIDs in neko container cgroup (works without docker recreate). +install -m 0755 /dev/stdin /usr/local/sbin/douyinweb-protect-neko-oom <<'EOF' +#!/bin/bash +set -euo pipefail +ADJ="${1:--800}" +for name in $(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' || true); do + cid=$(docker inspect -f '{{.Id}}' "$name") + # cgroup v2 path used by docker on this host + for base in \ + "/sys/fs/cgroup/system.slice/docker-${cid}.scope" \ + "/sys/fs/cgroup/docker/${cid}" \ + "/sys/fs/cgroup/system.slice/docker-${cid}.scope" + do + if [ -f "$base/cgroup.procs" ]; then + while read -r p; do + [ -n "$p" ] || continue + echo "$ADJ" > "/proc/$p/oom_score_adj" 2>/dev/null || true + done < "$base/cgroup.procs" + echo "protected $name via $base adj=$ADJ" + fi + done + # Also main pid + main=$(docker inspect -f '{{.State.Pid}}' "$name") + if [ -n "$main" ] && [ "$main" != "0" ]; then + echo "$ADJ" > "/proc/$main/oom_score_adj" 2>/dev/null || true + fi +done +EOF + +/usr/local/sbin/douyinweb-protect-neko-oom -800 + +# systemd timer every minute — re-apply after chrome spawn +cat > /etc/systemd/system/douyinweb-neko-oom-protect.service <<'EOF' +[Unit] +Description=Protect douyinweb Neko/Chrome from host OOM killer +After=docker.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/douyinweb-protect-neko-oom -800 +EOF +cat > /etc/systemd/system/douyinweb-neko-oom-protect.timer <<'EOF' +[Unit] +Description=Re-apply Neko OOM protection every minute + +[Timer] +OnBootSec=30s +OnUnitActiveSec=60s +AccuracySec=15s +Unit=douyinweb-neko-oom-protect.service + +[Install] +WantedBy=timers.target +EOF +systemctl daemon-reload +systemctl enable --now douyinweb-neko-oom-protect.timer +systemctl start douyinweb-neko-oom-protect.service + +echo ===HARD_RESTART_CHROME=== +# Kill entire chrome tree; browser-launch.sh loop relaunches with new memory flags. +docker exec douyinweb-neko-7 sh -c 'pkill -9 -f /opt/google/chrome/chrome 2>/dev/null; pkill -9 chrome 2>/dev/null; true' || true +sleep 8 + +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time, subprocess +from app import youtube_neko as yn +nid=7 +for i in range(30): + tabs=yn._cdp_fetch_tabs(nid) + pages=[t for t in tabs if (t.get("type") or "page")=="page"] + print("wait", i, len(pages)) + if pages: + break + time.sleep(2) +else: + raise SystemExit("chrome_did_not_return") + +# re-protect after spawn +subprocess.check_call(["/usr/local/sbin/douyinweb-protect-neko-oom", "-800"]) + +studio="https://studio.youtube.com/video/xmwiN6n4d9Q/livestreaming" +print(yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio)) +time.sleep(8) +sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0) +print("sig", json.dumps({k:sig.get(k) for k in ("ok","control_ready","live_status","on_air","url")}, ensure_ascii=False)) +print("text_head", str(sig.get("text") or "")[:200].replace("\n"," | ")) + +# verify cmdline has renderer-process-limit +code,out=yn._run(["docker","exec",yn._container_name(nid),"sh","-c", + "tr '\\0' '\\n' /dev/null; for p in /proc/[0-9]*; do c=$(tr '\\0' ' ' <$p/cmdline 2>/dev/null); case \"$c\" in *chrome*--type=zygote*|*chrome*--user-data-dir*) echo OOM=$(cat $p/oom_score_adj 2>/dev/null) $c | head -c 220; echo;; esac; done | head -20"], timeout=20) +print(out[:2500]) +# host view of container main oom +import os +main=int(subprocess.check_output(["docker","inspect","-f","{{.State.Pid}}","douyinweb-neko-7"], text=True).strip() or 0) +print("main_pid", main, "oom", open(f"/proc/{main}/oom_score_adj").read().strip() if main else None) +PY + +free -h +swapon --show +systemctl is-active sing-box frpp 'wg-quick@wg-dy' douyinweb-neko-oom-protect.timer +""", +) +c.close() +print("DONE", time.strftime("%H:%M:%S")) diff --git a/scripts/_apply_shorts_gap_settings.py b/scripts/_apply_shorts_gap_settings.py new file mode 100644 index 0000000..572f189 --- /dev/null +++ b/scripts/_apply_shorts_gap_settings.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +"""Set Shorts gap settings to 10min via API; report quota board. Do not toggle shorts_enabled.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def session(base: str): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=30) + return op + + +def call(op, base, path, method="GET", body=None, timeout=40): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + base + path, + data=data, + method=method, + headers={"Content-Type": "application/json"} if body is not None else {}, + ) + with op.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +for base in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + print(f"\n===== {base} =====") + op = session(base) + before = call(op, base, "/api/shorts/status") + print( + "before enabled=", before.get("enabled"), + "ch_gap=", before.get("channel_min_gap_sec"), + "up_gap=", before.get("upload_min_gap_sec"), + "board_gap=", (before.get("board") or {}).get("total_gap"), + "min_unmet=", (before.get("board") or {}).get("min_unmet"), + ) + # Only change gap rules — never flip shorts_enabled here. + patched = call( + op, + base, + "/api/settings", + method="PATCH", + body={ + "shorts_channel_min_gap_sec": 600, + "shorts_upload_min_gap_sec": 600, + "shorts_dedupe_room_day": True, + }, + ) + print("patched keys ok=", bool(patched)) + after = call(op, base, "/api/shorts/status") + print( + "after enabled=", after.get("enabled"), + "ch_gap=", after.get("channel_min_gap_sec"), + "up_gap=", after.get("upload_min_gap_sec"), + ) + board = after.get("board") or {} + chans = board.get("channels") or [] + unmet = [c for c in chans if c.get("enabled") and not c.get("min_met")] + print("min_unmet_count=", len(unmet), "total_gap=", board.get("total_gap"), "push_date=", board.get("push_date")) + for c in unmet[:8]: + print(" ", c.get("name"), "used=", c.get("used"), "min=", c.get("daily_min"), "max=", c.get("daily_max")) +print("done") diff --git a/scripts/_audit_dual_fleet_health.py b/scripts/_audit_dual_fleet_health.py new file mode 100644 index 0000000..38050ef --- /dev/null +++ b/scripts/_audit_dual_fleet_health.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Fleet self-check: dy + dylive neko chrome, mounts, API. Never recreate Neko.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [ + ("dylive", "107.173.30.245"), + ("dy", "108.174.50.68"), +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +SCRIPT = r""" +set +e +echo '=== host ===' +hostname; free -m | head -2; uptime +systemctl is-active douyinweb-api douyinweb-web 2>/dev/null +curl -sS -m 8 -o /dev/null -w 'api_health:%{http_code}\n' http://127.0.0.1:8014/api/health +curl -sS -m 8 -o /dev/null -w 'fe_youtube:%{http_code}\n' http://127.0.0.1:4015/youtube + +echo '=== browser-launch host ===' +file /opt/douyinWEB/backend/neko/browser-launch.sh 2>/dev/null || ls -la /opt/douyinWEB/backend/neko/browser-launch.sh +head -1 /opt/douyinWEB/backend/neko/browser-launch.sh | od -c | head -2 +grep -n 'jitless\|no-turbofan\|PassageEmbeddings\|no-wasm-simd' /opt/douyinWEB/backend/neko/browser-launch.sh | head -10 +sh -n /opt/douyinWEB/backend/neko/browser-launch.sh && echo launch_syntax_ok || echo launch_syntax_BAD + +echo '=== neko containers ===' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V + +echo '=== running neko chrome/supervisor ===' +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort -V); do + echo "--- $n ---" + # deleted mount? + del=$(docker exec "$n" sh -c 'cat /proc/self/mountinfo 2>/dev/null | grep browser-launch' | grep -c '//deleted' || true) + echo "browser_launch_deleted_mount=$del" + docker exec "$n" sh -c 'grep -n jitless /etc/neko/browser-launch.sh 2>/dev/null | head -1; sh -n /etc/neko/browser-launch.sh 2>/dev/null && echo syntax_ok || echo syntax_BAD' + st=$(docker exec "$n" supervisorctl status google-chrome 2>/dev/null | head -1) + echo "chrome: $st" + cdp=$(docker exec "$n" sh -c 'curl -sS -m 2 http://127.0.0.1:9222/json/version 2>/dev/null' | head -c 80) + echo "cdp: ${cdp:-FAIL}" +done + +echo '=== assign neko_enabled vs running ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db, db +cfg = db.get_settings_map() +print('auto', bool(cfg.get('youtube_relay_enabled') or cfg.get('youtube_relay_auto'))) +# try common keys +for k in ('youtube_relay_enabled','youtube_relay_pipeline_enabled','youtube_relay_auto_push'): + if k in cfg: print(k, cfg.get(k)) +print('time_slot', cfg.get('youtube_relay_time_slot_mode')) +print('exclusive', cfg.get('youtube_relay_exclusive_live')) +en=[] +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + nid=int(g.get('neko_instance_id') or 0) + if g.get('neko_enabled'): + en.append((g.get('name'), nid, g.get('category'))) +print('neko_enabled', en) +PY + +echo '=== relay status snippet ===' +CS=$(mktemp) +curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 15 -b "$CS" http://127.0.0.1:8014/api/youtube/relay/status | python3 - <<'PY' +import sys,json +d=json.load(sys.stdin) +print('enabled', d.get('enabled'), 'running', d.get('running'), 'pushing', d.get('pushing_count')) +print('douyin_live', d.get('douyin_live_count'), 'winner', d.get('exclusive_winner_group_id')) +s=d.get('settings') or {} +print('slot', s.get('youtube_relay_time_slot_mode'), 'excl', s.get('youtube_relay_exclusive_live')) +print('err', (d.get('last_error') or '')[:200]) +PY + +echo '=== FE marker ===' +grep -Rnl '普通频道 · 在播抖音' /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx 2>/dev/null | head -1 +grep -Rnl '普通频道 · 在播抖音' /opt/douyinWEB/frontend/.next/static 2>/dev/null | head -2 || echo 'marker_not_in_static_or_missing_build' + +echo HOST_CHECK_DONE +""" + +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=240) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + +print("ALL_HOSTS_DONE", flush=True) diff --git a/scripts/_audit_fix_neko6_remount_dy_api.py b/scripts/_audit_fix_neko6_remount_dy_api.py new file mode 100644 index 0000000..48c69d8 --- /dev/null +++ b/scripts/_audit_fix_neko6_remount_dy_api.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Ops: remount browser-launch on dylive neko-6 + check dy API. Never recreate.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +# --- dylive: remount browser-launch via container restart (volumes keep profile) --- +print("=== dylive neko-6 remount ===", flush=True) +dl = connect("107.173.30.245") +_i, o, e = dl.exec_command( + r""" +set +e +NAME=douyinweb-neko-6 +# ensure host launch script is LF + jitless +sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh +grep -n jitless /opt/douyinWEB/backend/neko/browser-launch.sh | head -1 +# restart remounts binds (NOT recreate) +docker restart "$NAME" +sleep 12 +docker exec "$NAME" sh -c 'cat /proc/self/mountinfo | grep browser-launch' +del=$(docker exec "$NAME" sh -c 'cat /proc/self/mountinfo | grep browser-launch' | grep -c '//deleted' || true) +echo deleted_mount=$del +docker exec "$NAME" supervisorctl status +docker exec "$NAME" sh -c 'curl -sS -m 5 http://127.0.0.1:9222/json/version | head -c 180; echo' +# if chrome fatal, start again +st=$(docker exec "$NAME" supervisorctl status google-chrome 2>/dev/null) +echo "$st" +case "$st" in + *FATAL*|*STOPPED*) + docker exec "$NAME" sh -c 'rm -f /home/neko/.config/google-chrome/Singleton*; supervisorctl start google-chrome; sleep 8; supervisorctl status google-chrome; curl -sS -m 5 http://127.0.0.1:9222/json/version | head -c 120; echo' + ;; +esac +free -m | head -2 +echo DYLIVE_OK +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +dl.close() + +# --- dy: API hang diagnose --- +print("=== dy API diagnose ===", flush=True) +dy = connect("108.174.50.68") +_i, o, e = dy.exec_command( + r""" +set +e +systemctl is-active douyinweb-api douyinweb-web +free -m | head -2 +ss -lntp | grep -E ':8014|:4015' || true +timeout 5 curl -sS -m 4 -o /dev/null -w 'health:%{http_code} time:%{time_total}\n' http://127.0.0.1:8014/api/health || echo health_timeout +journalctl -u douyinweb-api -n 40 --no-pager 2>/dev/null | tail -40 +# if hung workers, show top +ps aux --sort=-%mem | head -15 +echo DY_OK +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +dy.close() +print("DONE", flush=True) diff --git a/scripts/_audit_post_smoke.py b/scripts/_audit_post_smoke.py new file mode 100644 index 0000000..317b5be --- /dev/null +++ b/scripts/_audit_post_smoke.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Post-audit smoke: dy + dylive health, neko chrome, relay flags.""" +from __future__ import annotations + +import json +import sys +import time +import urllib.request +from http.cookiejar import CookieJar +import ssl + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def ssh(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + + +def run(c, cmd: str) -> str: + _i, o, e = c.exec_command(cmd, timeout=90) + return (o.read() + e.read()).decode("utf-8", "replace") + + +for label, host in (("dylive", "107.173.30.245"), ("dy", "108.174.50.68")): + print(f"\n## {label}", flush=True) + c = ssh(host) + print(run(c, r""" +set +e +free -m | head -2 +systemctl is-active douyinweb-api douyinweb-web +curl -sS -m 10 -o /dev/null -w 'health:%{http_code}\n' http://127.0.0.1:8014/api/health +curl -sS -m 10 -o /dev/null -w 'youtube:%{http_code}\n' http://127.0.0.1:4015/youtube +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + st=$(docker exec "$n" supervisorctl status google-chrome 2>/dev/null | awk '{print $1,$2}') + del=$(docker exec "$n" sh -c 'grep -c "//deleted" /proc/self/mountinfo' 2>/dev/null || echo 0) + echo "$n chrome=[$st] deleted_mount_hits=$del" +done +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +cfg=db.get_settings_map() +print('relay_enabled', cfg.get('youtube_relay_enabled')) +print('time_slot', cfg.get('youtube_relay_time_slot_mode')) +print('exclusive', cfg.get('youtube_relay_exclusive_live')) +PY +grep -n 'paused_exclusive' /opt/douyinWEB/backend/app/youtube_relay_status.py | head -2 +grep -n 'time_slot_mode on but no time_slot' /opt/douyinWEB/backend/app/youtube_relay_pipeline.py | head -1 +"""), flush=True) + c.close() + +print("\n## public", flush=True) +for base in ("https://dylive.nomadro.com", "https://dy.nomadro.live"): + try: + jar = CookieJar() + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar), urllib.request.HTTPSHandler(context=CTX)) + req = urllib.request.Request(f"{base}/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") + with opener.open(req, timeout=20) as r: + print(base, "login", r.status, flush=True) + with opener.open(urllib.request.Request(f"{base}/api/health"), timeout=15) as r: + print(base, "health", r.status, flush=True) + except Exception as e: + print(base, "ERR", e, flush=True) + +print("SMOKE_DONE", flush=True) diff --git a/scripts/_audit_project_health_dual.py b/scripts/_audit_project_health_dual.py new file mode 100644 index 0000000..0f90492 --- /dev/null +++ b/scripts/_audit_project_health_dual.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Broad read-only health sweep: dy + dylive (live/neko/shorts/yt-long/disk/quota).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] + +REMOTE = r''' +set +e +echo "=== host $(hostname) $(date -Is) ===" +echo "-- mem --" +free -h | head -3 +echo "-- disk --" +df -h / /opt /var/lib/docker 2>/dev/null | head -10 +echo "-- units --" +for u in douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; do + printf '%s ' "$u"; systemctl is-active "$u" 2>/dev/null; done +echo +echo "-- neko containers --" +docker ps -a --format '{{.Names}}\t{{.Status}}' 2>/dev/null | grep -i neko | sort +echo "-- oom/kill recent (journal 6h) --" +journalctl --since '6 hours ago' --no-pager 2>/dev/null | grep -iE 'Out of memory|oom-kill|Killed process|SIGILL|neko.*(exit|restart)|douyinweb-neko' | tail -25 +echo "-- api relay/shorts/ytlong via python --" +cd /opt/douyinWEB/backend && .venv/bin/python <<'PY' +import json, time +from app import db +from app.youtube_relay_pipeline import youtube_relay_pipeline +from app import yt_long_db +from app.shorts_yt_quota import quota_budgets_by_profile +from app.timeutil import push_date_from_ts +try: + from app import youtube_neko +except Exception as e: + youtube_neko = None + print("neko_import_err", e) + +cfg = db.get_settings_map() +day = push_date_from_ts(time.time()) +print("day", day) +print("relay_enabled", cfg.get("youtube_relay_enabled"), "exclusive", cfg.get("youtube_relay_exclusive_live")) +print("shorts_pipeline", cfg.get("shorts_enabled"), cfg.get("shorts_pipeline_enabled")) +print("yt_long", cfg.get("yt_long_enabled"), "disk_min", cfg.get("clips_min_free_gb")) +print("limited_day", cfg.get("yt_long_quota_limited_day"), str(cfg.get("yt_long_quota_limited_reason") or "")[:120]) +st = youtube_relay_pipeline.status() +print("relay_running", st.get("running"), "pushing", st.get("pushing_count"), "winner", st.get("exclusive_winner_group_id")) +# neko mismatch: running vs enabled +try: + from app import yt_assign_db + groups = yt_assign_db.list_groups(include_urls=False) + print("assign_groups", len(groups)) + mismatch = [] + for g in groups: + nid = int(g.get("neko_instance_id") or 0) + if nid < 1: + continue + en = bool(g.get("neko_enabled")) + state = youtube_neko._container_state(nid, check_http=False) if youtube_neko else {} + run = bool(state.get("running")) + if en != run: + mismatch.append((g.get("name"), nid, "enabled", en, "running", run, state.get("status"))) + print("neko_enabled_vs_running_mismatch", len(mismatch)) + for row in mismatch[:12]: + print(" ", row) +except Exception as e: + print("neko_mismatch_err", e) +print("yt_quota_budgets", json.dumps(quota_budgets_by_profile(cfg), ensure_ascii=False)[:900]) +print("yt_long_upload_used", yt_long_db.yt_long_upload_used(day), "daily_max", yt_long_db.yt_long_daily_max(cfg)) +try: + s = db.shorts_channels_quota_summary(day) + print("shorts_uploaded_sum", sum(int(r.get("uploaded") or 0) for r in s), "channels", len(s), "gap", sum(int(r.get("gap") or 0) for r in s)) +except Exception as e: + print("shorts_err", e) +# stuck jobs sample +try: + for stname in ("uploading", "recording", "pending"): + d = db.list_shorts_jobs(push_date=day, status=stname, limit=5, offset=0) + print(f"shorts_{stname}", d.get("total"), "sample", [ (j.get("id"), j.get("channel_name") or j.get("anchor_name"), j.get("error")) for j in (d.get("jobs") or [])[:3]]) +except Exception as e: + print("jobs_err", e) +try: + for stname in ("uploading", "recording", "scheduled", "pending"): + d = yt_long_db.list_yt_long_jobs_page(status=stname, push_date=day, limit=5, offset=0) + print(f"ytlong_{stname}", d.get("total")) +except Exception as e: + print("ytlong_jobs_err", e) +PY +echo "-- ffmpeg count --" +ps -eo pid,etime,cmd | grep -E '[f]fmpeg' | wc -l +echo "-- last api errors 2h --" +journalctl -u douyinweb-api --since '2 hours ago' --no-pager 2>/dev/null | grep -iE 'ERROR|Traceback|QUOTA|OOM|timeout|neko wait blocked|studio_not_on_air' | tail -30 +''' + + +def run_host(label: str, host: str) -> None: + print(f"\n########## {label} {host} ##########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + break + except Exception as e: + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(2 + i) + else: + print("ssh_fail", flush=True) + return + _, o, e = c.exec_command(REMOTE, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +for label, host in HOSTS: + run_host(label, host) diff --git a/scripts/_check_cookie_keys_both.py b/scripts/_check_cookie_keys_both.py new file mode 100644 index 0000000..ee75935 --- /dev/null +++ b/scripts/_check_cookie_keys_both.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") + +SQL = r''' +python3 - <<'PY' +import sqlite3, json +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +keys=c.execute("SELECT key FROM kv_settings ORDER BY 1").fetchall() +interesting=[k[0] for k in keys if any(x in k[0].lower() for x in ("cookie","oauth","token","proxy"))] +print("interesting_keys", interesting) +for k in interesting: + v=c.execute("SELECT value FROM kv_settings WHERE key=?",(k,)).fetchone()[0] + try: + parsed=json.loads(v) + if isinstance(parsed,str): + print(k, "str_len", len(parsed)) + elif isinstance(parsed,list): + print(k, "list_len", len(parsed)) + elif isinstance(parsed,dict): + print(k, "dict_keys", list(parsed.keys())[:12]) + else: + print(k, type(parsed).__name__, str(parsed)[:80]) + except Exception: + print(k, "raw_len", len(v or "")) +# rooms / shorts sample +print("rooms", c.execute("select count(*) from rooms").fetchone()[0]) +print("shorts", [(r[0], r[1], bool(r[2]), len(r[3] or "")) for r in c.execute("select id,name,oauth_ok,refresh_token from shorts_channels limit 5")]) +print("assign", [(r[0], r[1], len(r[2] or ""), r[3]) for r in c.execute("select id,name,stream_key,neko_enabled from yt_assign_groups")]) +c.close() +PY +''' + + +def run(spec, cmd): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*spec, timeout=40, banner_timeout=80, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +print("=== PHYSICAL ===") +run(PHYS, f"echo '4669805' | sudo -S -p '' bash -lc {repr(SQL)}") +print("=== DYLIVE ===") +run(VPS, SQL) diff --git a/scripts/_check_dy_neko7_now.py b/scripts/_check_dy_neko7_now.py new file mode 100644 index 0000000..e7ee1e7 --- /dev/null +++ b/scripts/_check_dy_neko7_now.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=180) +_i, o, e = c.exec_command( + r""" +set +e +docker exec douyinweb-neko-7 python3 -c ' +import json,urllib.request +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print((t.get("title") or "")[:80]) + print(" ", (t.get("url") or "")[:120]) +' +echo '---' +# stop unexpected neko-8 if we did not need it +docker stop douyinweb-neko-8 2>/dev/null && echo stopped_neko8 || true +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -2 +curl -sk -o /dev/null -w 'neko7:%{http_code}\n' https://dy.nomadro.live/neko/7/ +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_check_dy_svc.py b/scripts/_check_dy_svc.py new file mode 100644 index 0000000..fe714bd --- /dev/null +++ b/scripts/_check_dy_svc.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import paramiko, sys +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +i, o, e = c.exec_command("systemctl is-active douyinweb-api; systemctl is-active douyinweb-web", timeout=30) +print("dy_svc:", o.read().decode().strip().replace("\n", " / ")) +c.close() diff --git a/scripts/_check_dylive_after_neko_sync.py b/scripts/_check_dylive_after_neko_sync.py new file mode 100644 index 0000000..30f330c --- /dev/null +++ b/scripts/_check_dylive_after_neko_sync.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Read-only health check on dylive after youtube_neko sync — no changes.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + cmd = r""" +echo '=== units ===' +for u in douyinweb-api douyinweb-web douyinweb-pb douyinweb-yt; do + printf '%-18s %s\n' "$u" "$(systemctl is-active $u 2>/dev/null)" +done +echo '=== hash marker ===' +grep -n 'relay may leave Chrome\|_neko_ids_for_cdp_poll\|Evidence-first' /opt/douyinWEB/backend/app/youtube_neko.py | head -10 +echo '=== api smoke ===' +curl -sS -m 8 http://127.0.0.1:8014/api/health || true +echo +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import youtube_neko, yt_assign_db +ids = youtube_neko._neko_ids_for_cdp_poll() +print('cdp_poll_ids', ids) +# enabled groups still included +enabled=[] +running_disabled=[] +for g in yt_assign_db.list_groups(include_urls=False): + nid=int(g.get('neko_instance_id') or 0) + if nid<1: continue + en=bool(g.get('neko_enabled')) + try: + run=bool(youtube_neko._container_state(nid, check_http=False).get('running')) + except Exception: + run=False + if en: enabled.append(nid) + if (not en) and run: running_disabled.append(nid) +print('enabled_neko_ids', sorted(set(enabled))) +print('running_disabled_ids', sorted(set(running_disabled))) +# any active relay row studio snap +try: + from app.youtube_relay_pipeline import youtube_relay_pipeline + st = youtube_relay_pipeline.status() if hasattr(youtube_relay_pipeline,'status') else None +except Exception as e: + st=None + print('relay_status_err', type(e).__name__, str(e)[:120]) +# light: groups with running neko + snap +for g in yt_assign_db.list_groups(include_urls=False): + nid=int(g.get('neko_instance_id') or 0) + if nid not in ids: + continue + snap=youtube_neko.studio_snapshot_for_group(g, max_age_sec=180) + print('SNAP', g.get('name'), 'neko', nid, 'en', g.get('neko_enabled'), + 'page', snap.get('live_page_open'), 'air', snap.get('on_air'), + 'viewers', snap.get('viewer_count'), 'src', snap.get('detect_source') or snap.get('ui_source')) +PY +echo '=== ffmpeg ===' +pgrep -c ffmpeg || echo 0 +echo '=== neko running ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' 2>/dev/null +""" + _i, o, e = c.exec_command(cmd, timeout=90) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:1500], flush=True) + c.close() + print("CHECK_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_check_dylive_neko_after_stop.py b/scripts/_check_dylive_neko_after_stop.py new file mode 100644 index 0000000..c64b7f6 --- /dev/null +++ b/scripts/_check_dylive_neko_after_stop.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Check dylive neko fleet after WP stop.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) +_i, o, e = c.exec_command( + r""" +set +e +docker ps -a --filter name=douyinweb-neko --format '{{.Names}}\t{{.Status}}' +echo '---' +free -m | head -2 +# which assign has neko 12 / 19 +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + nid = g.get('neko_instance_id') + if nid in (12, 18, 19) or g.get('neko_enabled'): + print(g.get('name'), 'neko', nid, 'en', g.get('neko_enabled'), 'cat', g.get('category')) +PY +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_check_dylive_oauth_uri.py b/scripts/_check_dylive_oauth_uri.py new file mode 100644 index 0000000..fb67603 --- /dev/null +++ b/scripts/_check_dylive_oauth_uri.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +import json, sys, paramiko +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +cmd = r'''python3 - <<'PY' +import sqlite3, json +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +for k in ["shorts_oauth_redirect_uri","dy_cookie_updated_at"]: + v=json.loads(c.execute("select value from kv_settings where key=?",(k,)).fetchone()[0]) + print(k, v) +print("rooms", c.execute("select count(*) from rooms").fetchone()[0]) +print("shorts", c.execute("select count(*) from shorts_channels").fetchone()[0]) +print("assign", c.execute("select count(*) from yt_assign_groups").fetchone()[0]) +c.close() +PY''' +_i,o,e=c.exec_command(cmd, timeout=30) +print((o.read()+e.read()).decode("utf-8","replace")) +c.close() diff --git a/scripts/_check_keep_edge_svcs.py b/scripts/_check_keep_edge_svcs.py new file mode 100644 index 0000000..8161554 --- /dev/null +++ b/scripts/_check_keep_edge_svcs.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Confirm sing-box / frpp / wg stay active on VPS. Live flush.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = ( + "systemctl is-active sing-box frpp 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null; " + "systemctl is-enabled sing-box frpp 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null; " + "ss -lntp | grep -E ':(4014|7000|8999)\\b' || true; " + "wg show interfaces 2>/dev/null; " + "systemctl show -p ActiveState --value sing-box frpp" +) +_i, o, e = c.exec_command(cmd, timeout=40) +while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) +sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) +sys.stdout.flush() +c.close() +print("DONE", flush=True) diff --git a/scripts/_check_opsneko_login_left.py b/scripts/_check_opsneko_login_left.py new file mode 100644 index 0000000..0173e9d --- /dev/null +++ b/scripts/_check_opsneko_login_left.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +echo "===== regular neko cookie auth check =====" +for i in 1 2 3; do + python3 - </dev/null +stat /opt/douyinWEB/backend/data/ops_neko/profiles/*/Default/Cookies | grep -E 'File:|Modify|Size' + +echo "===== ops hub / assign pairing still in DB? =====" +python3 - <<'PY' +import sqlite3 +from pathlib import Path +for db in [ + Path('/opt/douyinWEB/backend/data/monitor.db'), + Path('/opt/douyinWEB/backend/data/ops_neko.db'), +]: + if not db.exists(): + print('missing', db); continue + print('DB', db, db.stat().st_size) + con=sqlite3.connect(f'file:{db}?mode=ro', uri=True) + cur=con.cursor() + cur.execute("select name from sqlite_master where type='table' order by 1") + tables=[r[0] for r in cur.fetchall()] + print(' tables', tables[:40]) + for t in tables: + if any(x in t.lower() for x in ('ops','neko','hub','cred','pair','assign','studio')): + try: + cur.execute(f'select count(*) from {t}') + print(f' {t}:', cur.fetchone()[0]) + except Exception as e: + print(' err', t, e) + con.close() +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_check_login_left.sh", "wb") as f: + f.write(SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_check_login_left.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_check_opsneko_open_url.py b/scripts/_check_opsneko_open_url.py new file mode 100644 index 0000000..94d635b --- /dev/null +++ b/scripts/_check_opsneko_open_url.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +_i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc '" + "curl -sS -m 8 -b /tmp/cj -c /tmp/cj -X POST http://127.0.0.1:8014/api/auth/login " + " -H \"Content-Type: application/json\" " + " -d \"{\\\"username\\\":\\\"hackrobot\\\",\\\"password\\\":\\\"Xiao4669805@\\\"}\" >/dev/null; " + "curl -sS -m 8 -b /tmp/cj http://127.0.0.1:8014/api/ops/neko | " + " python3 -c \"import sys,json; d=json.load(sys.stdin); " + "print(\\\"peer\\\", d.get(\\\"peer\\\",{}).get(\\\"effective_public_base\\\"), d.get(\\\"peer\\\",{}).get(\\\"cn_edge_usable\\\")); " + "inst=(d.get(\\\"instances\\\") or [{}])[0]; print(\\\"open_url\\\", inst.get(\\\"open_url\\\")); " + "print(\\\"running\\\", inst.get(\\\"running\\\"))\"" + "'", + timeout=40, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_cleanup_dylive_p0p1.py b/scripts/_cleanup_dylive_p0p1.py new file mode 100644 index 0000000..911038c --- /dev/null +++ b/scripts/_cleanup_dylive_p0p1.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""P0+P1 cleanup on dylive (authorized). Seaweed inspect only in this pass.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def run(c, cmd, timeout=300): + print(f"\n===== {cmd[:120]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + start = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.recv_stderr_ready(): + sys.stdout.write(chan.recv_stderr(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.15) + code = chan.recv_exit_status() + print(f"\n[exit {code}]", flush=True) + return code + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh try {i}", flush=True) + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as ex: + print(ex, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + # --- P0 --- + print("\n######## P0 ########", flush=True) + run( + c, + r""" +set -e +echo BEFORE=$(df -h / | awk 'NR==2{print $3,$4,$5}') +# docker build cache +docker builder prune -af +# journal +journalctl --vacuum-size=300M +# .next.bak* keep .next +cd /opt/douyinWEB/frontend +ls -d .next.bak* 2>/dev/null || true +rm -rf .next.bak* +# /tmp deploy tgz +rm -f /tmp/next-*.tgz /tmp/dy_next_*.tgz /tmp/dy-next-*.tgz /tmp/next-fe-*.tgz /tmp/src-*.tgz /tmp/pb.zip 2>/dev/null || true +ls -lh /tmp/*.tgz /tmp/*.zip 2>/dev/null | head -20 || echo tmp_tgz_cleared +# apt +apt-get clean || true +echo AFTER_P0=$(df -h / | awk 'NR==2{print $3,$4,$5}') +""", + timeout=400, + ) + + # --- P1 --- + print("\n######## P1 ########", flush=True) + run( + c, + r""" +set -e +BK=/opt/douyinWEB/backend/data/backups +# keep newest 3 monitor backups +cd "$BK" +ls -1t monitor_*.db 2>/dev/null | tail -n +4 | while read f; do rm -f -- "$f"; echo del_bak "$f"; done +echo bak_left=$(ls -1 monitor_*.db 2>/dev/null | wc -l) bak_size=$(du -sh "$BK" | awk '{print $1}') +# npm / cache +rm -rf /root/.npm /root/.cache +# .local: only clear obvious caches if present +du -sh /root/.local/* 2>/dev/null | sort -h | tail -20 || true +rm -rf /root/.local/share/Trash /root/.local/share/pip /root/.local/lib 2>/dev/null || true +# docker exited containers + dangling images +docker container prune -f +docker image prune -f +echo AFTER_P1=$(df -h / | awk 'NR==2{print $3,$4,$5}') +docker system df +""", + timeout=300, + ) + + # seaweed layout inspect for 2-day retention + print("\n######## SEAWEED INSPECT ########", flush=True) + run( + c, + r""" +df -h / /data +du -sh /data/seaweed /data/seaweed/* 2>/dev/null +find /data/seaweed -maxdepth 3 -type d 2>/dev/null | head -40 +# sample object keys via weed / s3 if possible +ls -la /data/seaweed/volume 2>/dev/null | head -20 +# env for s3 +grep -E 'S3|SEAWEED|AWS|covers' /opt/douyinWEB/backend/.env /etc/systemd/system/douyinweb-*.service 2>/dev/null | head -40 +""", + timeout=60, + ) + c.close() + print("CLEANUP_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_clone_tm_les_to_ops.py b/scripts/_clone_tm_les_to_ops.py new file mode 100644 index 0000000..2fd5e64 --- /dev/null +++ b/scripts/_clone_tm_les_to_ops.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +echo --- profile8 --- +P8=/opt/douyinWEB/backend/data/neko/profiles/8/Default/Local\ Extension\ Settings/$EXT +ls -la "$P8" | head +grep -aR "YouTube Studio Auto Dismiss" "$P8" | wc -l +grep -ao "YouTube Studio Auto Dismiss" "$P8"/* 2>/dev/null | head +echo --- seed --- +SEED=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/$EXT +ls -la "$SEED" | head +grep -aR "YouTube Studio Auto Dismiss" "$SEED" | wc -l +# Try installAsSystemScripts true and reimport +python3 - <<'"'"'PY'"'"' +import json +from pathlib import Path +p=Path("/opt/douyinWEB/backend/neko/policies/policies.json") +d=json.loads(p.read_text()) +ji=d["3rdparty"]["extensions"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]["jsonImport"][0] +ji["installAsSystemScripts"]=True +p.write_text(json.dumps(d,ensure_ascii=False,indent=2)+"\n") +print("set installAsSystemScripts", ji) +PY +for i in 1 2; do + name=douyinweb-ops-neko-$i + docker exec "$name" supervisorctl stop google-chrome || true + sleep 1 + # clone profile8 LES if it has script + if grep -aq "YouTube Studio Auto Dismiss" $P8/* 2>/dev/null; then + echo cloning_from_profile8_to_ops$i + docker exec "$name" bash -lc "rm -rf /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT /home/neko/.config/google-chrome/Default/Managed\ Extension\ Settings/$EXT" + docker cp "$P8" "$name:/home/neko/.config/google-chrome/Default/Local Extension Settings/$EXT" + docker exec "$name" bash -lc "rm -f /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT/LOCK; chown -R neko:neko /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT" + else + echo profile8_empty_try_system_import + docker exec "$name" bash -lc "rm -rf /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT /home/neko/.config/google-chrome/Default/Managed\ Extension\ Settings/$EXT" + fi + docker exec "$name" supervisorctl start google-chrome +done +sleep 20 +for i in 1 2; do + echo ===== OPS$i ===== + docker exec douyinweb-ops-neko-$i bash -lc " + P=/home/neko/.config/google-chrome/Default + du -sh \"\$P/Local Extension Settings/$EXT\" 2>/dev/null + echo HITS=\$(grep -aR \"YouTube Studio Auto Dismiss\" \"\$P/Local Extension Settings/$EXT\" 2>/dev/null | wc -l) + strings \"\$P/Local Extension Settings/$EXT\"/* 2>/dev/null | grep -E \"2\\.2\\.|Auto Dismiss\" | head -8 + " +done +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_api_bind_docker.py b/scripts/_cmp_api_bind_docker.py new file mode 100644 index 0000000..7d10b97 --- /dev/null +++ b/scripts/_cmp_api_bind_docker.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Compare API bind + docker networking: dylive (good) vs dy.""" +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +CMD = r""" +echo '=== uvicorn / unit ===' +systemctl cat douyinweb-api 2>/dev/null | grep -E 'ExecStart|Environment|Host|8014' | head -30 +ps aux | grep -E 'uvicorn app.main' | grep -v grep | head -3 +echo '=== listen ===' +ss -lntp | grep 8014 || true +echo '=== docker network ===' +docker network ls +NAME=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | head -1) +docker inspect "$NAME" --format 'NetworkMode={{.HostConfig.NetworkMode}} ExtraHosts={{json .HostConfig.ExtraHosts}}' +docker inspect "$NAME" --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} IP={{$v.IPAddress}} GW={{$v.Gateway}}{{end}}' +echo '=== curl from container to health ===' +for u in \ + 'http://172.17.0.1:8014/api/health' \ + 'http://host.docker.internal:8014/api/health' \ + 'https://dy.nomadro.live/api/health' \ + 'https://dylive.nomadro.com/api/health'; do + code=$(docker exec "$NAME" curl -sS -m 5 -o /dev/null -w '%{http_code}' "$u" 2>/dev/null || echo fail) + echo "$code $u" +done +""" + +def run(host, name): + print(f"\n===== {name} {host} =====", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=60) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:600], flush=True) + c.close() + +run("107.173.30.245", "dylive") +run("108.174.50.68", "dy") +print("DONE", flush=True) diff --git a/scripts/_cmp_assign_cards_youtubei.py b/scripts/_cmp_assign_cards_youtubei.py new file mode 100644 index 0000000..85b191d --- /dev/null +++ b/scripts/_cmp_assign_cards_youtubei.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare assign channel cards + youtubei probe on physical vs VPS.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import asyncio, json, os, sys +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app import yt_assign_db, db +from app import youtube_client +from app import youtube_live + +async def main(): + groups = yt_assign_db.list_groups(include_urls=False) + print("ASSIGN_N", len(groups)) + cards = [] + for g in groups: + if not g.get("enabled"): + continue + cid = str(g.get("youtube_channel_id") or "").strip() + pk = str(g.get("channel_pk") or "").strip() + name = str(g.get("name") or "") + if cid or pk: + cards.append((name, cid, pk, str(g.get("id") or "")[:8])) + print("ENABLED_WITH_CH", len(cards)) + for row in cards[:20]: + print(" ", row) + + # what live-map currently probes (channel_groups + shorts only?) + cg = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or []) + shorts = db.list_shorts_channels() + print("channel_groups", len(cg), "shorts", len(shorts)) + + urls = [] + for name, cid, pk, gid in cards: + if cid: + urls.append(f"https://www.youtube.com/channel/{cid}") + urls = list(dict.fromkeys(urls)) + print("PROBE_URLS", len(urls)) + if urls: + try: + h = await youtube_client.health() + print("yt_svc_health", h) + except Exception as ex: + print("yt_svc_health_err", ex) + try: + data = await youtube_client.batch_live(urls[:15]) + live_n = 0 + for r in (data.get("results") or []): + if r.get("is_live"): + live_n += 1 + print(" LIVE", r.get("input"), (r.get("live") or {}).get("title") or r.get("title")) + else: + print(" off ", str(r.get("input") or "")[-30:], "err", (r.get("error") or "")[:60]) + print("batch_live_count", live_n, "/", len(data.get("results") or [])) + except Exception as ex: + print("batch_live_err", type(ex).__name__, ex) + + m = await youtube_live.build_live_map(force=True) + print("live_map_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:100]) + +asyncio.run(main()) +''' + + +def run(label, host, port, user, pwd, sudo=False): + print(f"\n######## {label} ########") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pwd, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_cmp_cards_yt.py", "w") as f: + f.write(REMOTE) + sftp.close() + py = "/opt/douyinWEB/backend/.venv/bin/python" + cmd = f"{py} /tmp/_cmp_cards_yt.py" + if sudo: + cmd = f"echo '{pwd}' | sudo -S -p '' {cmd}" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")[:4000]) + c.close() + + +def main(): + run("dylive/VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) + run("dy/physical", "107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_browser_launch_phys.py b/scripts/_cmp_browser_launch_phys.py new file mode 100644 index 0000000..5e524dc --- /dev/null +++ b/scripts/_cmp_browser_launch_phys.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare host browser-launch.sh with local; show if mangled.""" +from __future__ import annotations + +import hashlib +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend/neko/browser-launch.sh" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + remote = sftp.file("/opt/douyinWEB/backend/neko/browser-launch.sh", "r").read() + sftp.close() + local = LOCAL.read_bytes() + print("local_sha", hashlib.sha256(local).hexdigest()[:16], "len", len(local)) + print("remote_sha", hashlib.sha256(remote).hexdigest()[:16], "len", len(remote)) + print("same", local == remote) + text = remote.decode("utf-8", "replace") + print("--- remote first 40 lines ---") + print("\n".join(text.splitlines()[:40])) + print("--- remote grep profile_dir / extension_flags / set - ---") + for i, line in enumerate(text.splitlines(), 1): + if any( + x in line + for x in ( + "profile_dir=", + "extension_flags", + "set -", + "tm_load_dir", + "launch_browser", + "browser_pid", + ) + ): + print(f"{i}:{line}") + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_dual_ffmpeg_sources.py b/scripts/_cmp_dual_ffmpeg_sources.py new file mode 100644 index 0000000..84d6ec7 --- /dev/null +++ b/scripts/_cmp_dual_ffmpeg_sources.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Compare live FFmpeg inputs on both VPS — same source claim.""" +from __future__ import annotations + +import re +import sys +import time +import urllib.parse + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +PASS = "Xiao4669805" + +SCRIPT = r""" +set +e +echo '=== ffmpeg procs ===' +ps -eo pid,pcpu,pmem,etime,cmd | grep '[f]fmpeg' | head -5 +echo +echo '=== parse input url ===' +python3 - <<'PY' +import subprocess, re, urllib.parse +out=subprocess.check_output(['ps','-eo','args'], text=True, errors='replace') +for line in out.splitlines(): + if 'ffmpeg' not in line or 'rtmps://' not in line: continue + if line.strip().startswith('grep'): continue + # input after -i + m=re.search(r'-i\s+(\S+)', line) + vin=m.group(1).strip('"') if m else '' + # output rtmps + mo=re.search(r'(rtmps://\S+)', line) + vout=mo.group(1) if mo else '' + # scale + ms=re.search(r'scale=([^:\\s]+)', line) + scale=ms.group(1) if ms else '' + mb=re.search(r'-b:v\s+(\S+)', line) + br=mb.group(1) if mb else '' + mt=re.search(r'-threads\s+(\S+)', line) + th=mt.group(1) if mt else '' + print('INPUT', vin[:220]) + # classify + low=vin.lower() + kind='unknown' + for k in ('uhd','origin','hd','sd','ld','md','_or4','_hd','_sd','_ld'): + if k in low: kind=k; break + # unique_id / stream id + qs=urllib.parse.urlparse(vin) + q=urllib.parse.parse_qs(qs.query) + print('host', qs.hostname) + print('path', qs.path[-80:]) + print('unique_id', (q.get('unique_id') or [''])[0][:120]) + print('kind_hint', kind) + print('scale', scale, 'b:v', br, 'threads', th) + print('OUT', vout[:100]) + print('CPU_LINE_has_uhd', '_uhd' in vin or 'uhd' in vin.lower()) +PY +echo +echo '=== relay status brief ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import json +with _lock: + conn=_connect() + try: + rows=conn.execute("SELECT group_id, status, substr(source_url,1,120), substr(coalesce(last_error,''),1,60) FROM yt_relay_states WHERE status LIKE '%push%' OR status LIKE '%live%' OR is_pushing=1 LIMIT 10").fetchall() + except Exception: + try: + cols=[r[1] for r in conn.execute('PRAGMA table_info(yt_relay_states)').fetchall()] + print('relay_cols', cols) + rows=conn.execute('SELECT * FROM yt_relay_states LIMIT 5').fetchall() + for r in rows: print(dict(r)) + rows=[] + except Exception as e: + print('err', e); rows=[] + for r in rows: + print('relay', r) + # groups currently pushing via names + try: + for r in conn.execute("SELECT name, neko_instance_id, neko_enabled FROM yt_assign_groups").fetchall(): + pass + except Exception: pass +PY +# from API local +curl -sS -m 8 http://127.0.0.1:8014/api/youtube/relay/status 2>/dev/null | python3 - <<'PY' +import sys,json +raw=sys.stdin.read() +try: + d=json.loads(raw) +except Exception as e: + print('json_fail', e, raw[:200]); raise SystemExit +entries=d.get('entries') or d.get('groups') or d.get('items') or [] +if isinstance(d, dict) and not entries: + # maybe {group_id: {...}} + if all(isinstance(v, dict) for v in d.values()): + entries=[{'group_id':k, **v} for k,v in d.items() if isinstance(v, dict)] +print('keys', list(d.keys())[:20]) +if isinstance(entries, list): + for e in entries[:12]: + if not isinstance(e, dict): + continue + pushing=e.get('is_pushing') or e.get('pushing') or (str(e.get('status') or '').lower() in ('pushing','live','on_air')) + src=str(e.get('source_url') or e.get('douyin_url') or e.get('input_url') or '')[:100] + name=e.get('name') or e.get('group_name') or e.get('title') or '' + if pushing or src: + print({ + 'name': str(name)[:40], + 'pushing': pushing, + 'status': e.get('status') or e.get('phase'), + 'src': src, + 'fps': e.get('fps') or e.get('ffmpeg_fps'), + 'bitrate': e.get('bitrate') or e.get('speed'), + }) +PY +echo HOST_DONE +""" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2) + raise SystemExit("ssh fail") + + +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_cmp_dy_dylive_cpu.py b/scripts/_cmp_dy_dylive_cpu.py new file mode 100644 index 0000000..d96f6c5 --- /dev/null +++ b/scripts/_cmp_dy_dylive_cpu.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Compare dy vs dylive CPU/ffmpeg/neko — read only.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +HOSTS = [ + ("dy", "108.174.50.68"), + ("dylive", "107.173.30.245"), +] + +CMD = r""" +echo HOST=$(hostname) +echo UPTIME=$(uptime) +echo CORES=$(nproc) +free -h | head -2 +echo '---TOP---' +ps -eo pcpu,pmem,rss,comm,args --sort=-pcpu | head -18 +echo '---FFMPEG---' +pgrep -a ffmpeg 2>/dev/null | while read -r line; do + pid=$(echo "$line" | awk '{print $1}') + cpu=$(ps -p "$pid" -o pcpu=,rss= 2>/dev/null) + # extract input url quality hint + echo "PID $pid CPU/RSS $cpu" + echo "$line" | tr ' ' '\n' | grep -E '_uhd|_hd|_sd|ORIGIN|rtmps|yt_long|clips/' | head -8 + echo '---' +done +echo ffmpeg_n=$(pgrep -c ffmpeg 2>/dev/null || echo 0) +echo '---NEKO---' +docker ps --filter name=neko --format '{{.Names}} {{.Status}}' 2>/dev/null +docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}' 2>/dev/null | grep neko || true +echo '---API---' +ps -eo pcpu,pmem,rss,args | grep -E 'uvicorn app.main|next-server' | grep -v grep +echo '---LOADSRC---' +# soft decode clue: threads / preset in ffmpeg +pgrep -a ffmpeg 2>/dev/null | grep -oE '\-threads [0-9]+|\-preset [a-z0-9]+|\-b:v [^ ]+|\-vf [^ ]+' | head -40 +""" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", PASS, timeout=25, allow_agent=False, look_for_keys=False) + return c + except Exception as e: + print(f"ssh {host} fail {e}", flush=True) + time.sleep(1 + i) + raise SystemExit(f"ssh_fail {host}") + + +def main(): + for name, host in HOSTS: + print(f"\n########## {name} {host} ##########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(CMD, timeout=45) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:500], flush=True) + c.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_dylive_dy_neko_studio.py b/scripts/_cmp_dylive_dy_neko_studio.py new file mode 100644 index 0000000..03632c6 --- /dev/null +++ b/scripts/_cmp_dylive_dy_neko_studio.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Compare dylive (good) vs dy (broken) for Studio scrape / neko — read only.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +LOCAL = Path(r"c:\Users\admin\Desktop\douyinWEB\backend\app\youtube_neko.py") + + +CMD = r""" +echo HOST=$(hostname) +echo api=$(systemctl is-active douyinweb-api) +sha256sum /opt/douyinWEB/backend/app/youtube_neko.py | awk '{print "neko_py",$1}' +# markers +grep -c 'relay may leave Chrome' /opt/douyinWEB/backend/app/youtube_neko.py || echo marker0 +grep -c 'Evidence-first' /opt/douyinWEB/backend/app/youtube_neko.py || true +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import youtube_neko, yt_assign_db + +def st(nid): + try: + return bool(youtube_neko._container_state(nid, check_http=False).get('running')) + except Exception: + return False + +print('cdp_poll_ids', youtube_neko._neko_ids_for_cdp_poll()) +rows=[] +for g in yt_assign_db.list_groups(include_urls=False): + nid=int(g.get('neko_instance_id') or 0) + if nid<1: continue + run=st(nid) + en=bool(g.get('neko_enabled')) + if not (en or run): + continue + snap=youtube_neko.studio_snapshot_for_group(g, max_age_sec=180) + rows.append({ + 'name': g.get('name'), + 'nid': nid, + 'neko_enabled': en, + 'running': run, + 'prefer': g.get('neko_open_prefer'), + 'ops_slot': int(g.get('ops_neko_slot') or 0), + 'page': snap.get('live_page_open'), + 'air': snap.get('on_air'), + 'viewers': snap.get('viewer_count'), + 'src': snap.get('detect_source') or '', + 'ui': snap.get('ui_source') or '', + 'url': (snap.get('url') or '')[:70], + }) +print('active_groups', len(rows)) +for r in rows: + print(json.dumps(r, ensure_ascii=False)) + +# docker +import subprocess +out=subprocess.check_output(['docker','ps','--filter','name=douyinweb-neko','--format','{{.Names}} {{.Status}}'], text=True) +print('DOCKER') +print(out.strip() or '(none)') +PY +""" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + return c + except Exception as e: + print(host, e, flush=True) + time.sleep(1 + i) + raise SystemExit(f"fail {host}") + + +def main(): + print("local_neko_py", hashlib.sha256(LOCAL.read_bytes()).hexdigest()[:12], flush=True) + for name, host in HOSTS: + print(f"\n########## {name} {host} ##########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(CMD, timeout=90) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:800], flush=True) + c.close() + print("CMP_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_ext_hub_reach.py b/scripts/_cmp_ext_hub_reach.py new file mode 100644 index 0000000..f694214 --- /dev/null +++ b/scripts/_cmp_ext_hub_reach.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Compare live-ops extension hub reachability: dylive vs dy.""" +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +CMD = r""" +echo HOST=$(hostname) +# extension files in running container vs host mount +NAME=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | head -1) +echo CONTAINER=$NAME +docker exec "$NAME" head -20 /etc/neko/live-ops-extension/background.js +echo '--- host file ---' +head -20 /opt/douyinWEB/backend/neko/live-ops-extension/background.js +echo '--- from container curl hubs ---' +for u in \ + 'http://host.docker.internal:8014/api/health' \ + 'http://172.17.0.1:8014/api/health' \ + 'http://127.0.0.1:8014/api/health'; do + echo -n "$u -> " + docker exec "$NAME" curl -sS -m 3 -o /dev/null -w '%{http_code}' "$u" 2>/dev/null || echo fail + echo +done +# gateway IP +docker exec "$NAME" getent hosts host.docker.internal 2>/dev/null || true +ip -4 addr show docker0 2>/dev/null | head -3 +# recent ingest hits +journalctl -u douyinweb-api --since '20 min ago' --no-pager | grep -c 'live/ingest' || true +journalctl -u douyinweb-api --since '20 min ago' --no-pager | grep 'live/ingest' | tail -5 +# compare content.js hash +sha256sum /opt/douyinWEB/backend/neko/live-ops-extension/*.js | awk '{print $2,$1}' +docker exec "$NAME" sha256sum /etc/neko/live-ops-extension/background.js /etc/neko/live-ops-extension/content.js 2>/dev/null +""" + +def run(host, name): + print(f"\n===== {name} =====", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=60) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:800], flush=True) + c.close() + +run("107.173.30.245", "dylive") +run("108.174.50.68", "dy") +print("DONE", flush=True) diff --git a/scripts/_cmp_live_map_ssh.py b/scripts/_cmp_live_map_ssh.py new file mode 100644 index 0000000..4e9e740 --- /dev/null +++ b/scripts/_cmp_live_map_ssh.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare live-map counts on VPS vs physical via SSH (no auth).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import asyncio, json, os, sys +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app import youtube_live +from app import youtube_relay_pipeline as yrp + +async def main(): + m = await youtube_live.build_live_map(force=True) + entries = m.get("entries") or {} + live = [(k, v.get("source"), (v.get("title") or "")[:40]) for k,v in entries.items() if v.get("is_live")] + print("live_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:120]) + print("live_entries", len(live)) + for row in live[:20]: + print(" ", row) + st = yrp.youtube_relay_pipeline.status() + pushing = [g for g in (st.get("groups") or []) if g.get("is_pushing") or str(g.get("status") or "") == "pushing"] + print("relay_pushing", len(pushing)) + for g in pushing[:8]: + print(" ", g.get("group_id"), g.get("name") or g.get("title"), g.get("status")) + +asyncio.run(main()) +''' + + +def probe(label, host, port, user, pwd, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pwd, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_cmp_live_map.py", "w") as f: + f.write(REMOTE) + sftp.close() + py = "/opt/douyinWEB/backend/.venv/bin/python" + cmd = f"{py} /tmp/_cmp_live_map.py" + if sudo: + cmd = f"echo '{pwd}' | sudo -S -p '' {cmd}" + _, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")[:2500]) + c.close() + + +def main(): + probe("dylive/VPS", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + probe("dy/physical", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_neko_tm_phys_vps.py b/scripts/_cmp_neko_tm_phys_vps.py new file mode 100644 index 0000000..582b9bd --- /dev/null +++ b/scripts/_cmp_neko_tm_phys_vps.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare TM + login on physical vs VPS assign Nekos (douyinweb-neko-*).""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +INSIDE = r''' +import json, os, re, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +base=Path("/home/neko/.config/google-chrome/Default") +pref=base/"Preferences" +e={} +ai=[] +if pref.exists(): + d=json.loads(pref.read_text(encoding="utf-8", errors="replace")) + e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} + ai=d.get("account_info") or [] +emails=[a.get("email") for a in ai if isinstance(a, dict) and a.get("email")] if isinstance(ai, list) else [] +print("emails", emails) +print("tm_state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore"), "disable", e.get("disable_reasons")) +sp=base/"Secure Preferences" +print("secure_bytes", sp.stat().st_size if sp.exists() else None) +ext_dir=base/"Extensions"/ext +print("ext_exists", ext_dir.exists()) +les=base/"Local Extension Settings"/ext +print("les_exists", les.exists(), "les_files", len(list(les.iterdir())) if les.exists() else 0) +# load-extension +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: + cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00", b" ").decode("utf-8","replace") + except Exception: + continue + if "google-chrome" in cmd and "--type=" not in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_ext", m.group(1) if m else "NONE") + found=True + break +if not found: + print("load_ext NO_CHROME") +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3).read()) +except Exception as ex: + print("cdp_err", type(ex).__name__); tabs=[] +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw)) +# script in LES +hits=0 +if les.exists(): + for p in les.rglob("*"): + if p.is_file() and p.stat().st_size < 20_000_000: + try: + raw=p.read_bytes() + except Exception: + continue + if b"YouTube Studio Auto Dismiss" in raw: + hits+=1 +print("script_hits", hits) +try: + pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) + print("forcelist", pol.get("ExtensionInstallForcelist")) +except Exception as ex: + print("pol_err", ex) +''' + +HOST_CHECK = r''' +echo "=== host browser-launch / policies ===" +grep -nE "Offline Tampermonkey|tm_load_dir|load-extension" /opt/douyinWEB/backend/neko/browser-launch.sh | head -15 +python3 - <<'PY' +import json +from pathlib import Path +p=Path("/opt/douyinWEB/backend/neko/policies/policies.json") +d=json.loads(p.read_text()) +print("host_forcelist", d.get("ExtensionInstallForcelist")) +print("host_jsonImport", bool((((d.get("3rdparty") or {}).get("extensions") or {}).get("dhdgffkkebhmkfjojejmpbldmpobfkfo") or {}).get("jsonImport"))) +seed=Path("/opt/douyinWEB/backend/neko/tampermonkey-seed/Default") +print("seed_ext", (seed/"Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo").exists()) +print("seed_les", (seed/"Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo").exists()) +pref=seed/"Preferences" +if pref.exists(): + e=((json.loads(pref.read_text()).get("extensions") or {}).get("settings") or {}).get("dhdgffkkebhmkfjojejmpbldmpobfkfo") or {} + print("seed_pref loc", e.get("location"), "webstore", e.get("from_webstore")) +PY +echo "=== containers ===" +docker ps -a --format "{{.Names}} {{.Status}}" | grep -E "douyinweb-neko-[0-9]+$" | sort +''' + + +def probe(label: str, host: str, port: int, user: str, password: str, sudo: bool, slots: list[int]) -> None: + print(f"\n########## {label} ##########") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, password, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_cmp_neko_tm_host.sh", "wb") as f: + f.write(HOST_CHECK.encode()) + with sftp.file("/tmp/_cmp_neko_tm_inside.py", "wb") as f: + f.write(INSIDE.encode()) + sftp.close() + prefix = f"echo {password} | sudo -S -p '' " if sudo else "" + out = _run(c, f"{prefix}bash /tmp/_cmp_neko_tm_host.sh", 60) + print(out) + for i in slots: + name = f"douyinweb-neko-{i}" + print(f"----- {name} -----") + cmd = ( + f"{prefix}bash -lc 'docker ps --format {{{{.Names}}}} | grep -qx {name} || {{ echo NOT_RUNNING; exit 0; }}; " + f"docker exec -i {name} python3 - < /tmp/_cmp_neko_tm_inside.py'" + ) + # stdin via docker exec -i needs file inside container + cmd = f"""{prefix}bash -lc ' +if ! docker ps --format "{{{{.Names}}}}" | grep -qx {name}; then echo NOT_RUNNING; exit 0; fi +docker exec -i {name} tee /tmp/_cmp_neko_tm_inside.py < /tmp/_cmp_neko_tm_inside.py >/dev/null +docker exec {name} python3 /tmp/_cmp_neko_tm_inside.py +'""" + print(_run(c, cmd, 60)) + c.close() + + +def _run(c, cmd, timeout=60) -> str: + _i, o, e = c.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def main() -> None: + # Physical via FRP :4014 + probe("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True, [1, 2, 3, 7, 8]) + # VPS direct + probe("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False, [1, 2, 3, 7, 8]) + + +if __name__ == "__main__": + main() diff --git a/scripts/_cmp_studio_scrape_quality.py b/scripts/_cmp_studio_scrape_quality.py new file mode 100644 index 0000000..8531d10 --- /dev/null +++ b/scripts/_cmp_studio_scrape_quality.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Deep compare studio scrape quality: dylive vs dy.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" + + +CMD = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import youtube_neko + +ids = youtube_neko._neko_ids_for_cdp_poll() +print('ids', ids) +# force one CDP poll +r = youtube_neko.poll_studio_cdp_once() +print('poll', json.dumps(r, ensure_ascii=False)[:2000]) +for nid in ids: + # raw cdp + sig = youtube_neko._cdp_studio_page_signals(nid, force=True) + print('CDP', nid, json.dumps({k:sig.get(k) for k in ( + 'ok','error','url','on_air','live_status','viewer_count','total_views','health','text' + ) if k in sig or True}, ensure_ascii=False, default=str)[:800]) + snap = youtube_neko.studio_snapshot_for_instance(nid, max_age_sec=120, allow_cdp=True) + print('SNAP', nid, json.dumps({k:snap.get(k) for k in ( + 'live_page_open','on_air','viewer_count','total_views','detect_source','url','age_sec' + )}, ensure_ascii=False)) + +# extension instance id + recent telemetry +youtube_neko._bootstrap_studio_telemetry_from_disk() +print('refs', list(getattr(youtube_neko,'_studio_latest_by_ref',{}).keys())[:20]) +print('by_neko', list(getattr(youtube_neko,'_studio_latest_by_neko',{}).keys())[:20]) +for nid in ids: + ev = youtube_neko._studio_latest_by_neko.get(nid) + if ev: + print('EV', nid, 'age', round(time.time()-float(ev.get('received_at') or 0),1), + 'keys', list((ev.get('payload') or {}).keys())[:20]) + p=ev.get('payload') or {} + print(' viewers', p.get('viewer_count'), 'total', p.get('total_views'), 'src', p.get('source'), 'url', str(p.get('url') or '')[:80]) +PY + +echo '=== extension in container ===' +for id in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sed 's/.*-//'); do + echo "neko-$id instance_id=$(docker exec douyinweb-neko-$id cat /etc/neko/live-ops-extension/instance_id.txt 2>/dev/null)" + docker exec douyinweb-neko-$id ls /etc/neko/live-ops-extension/content.js 2>/dev/null && \ + docker exec douyinweb-neko-$id wc -c /etc/neko/live-ops-extension/content.js +done +echo '=== recent studio samples ===' +sqlite3 /opt/douyinWEB/backend/data/monitor.db \ + "SELECT datetime(ts,'unixepoch'), neko_ref, live_page_open, on_air, viewer_count, total_views, substr(studio_url,1,60), detect_source FROM yt_studio_samples ORDER BY ts DESC LIMIT 6;" 2>/dev/null || \ +python3 - <<'PY' +import sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +for r in con.execute('SELECT ts,neko_ref,live_page_open,on_air,viewer_count,total_views,studio_url,detect_source FROM yt_studio_samples ORDER BY ts DESC LIMIT 6'): + print(dict(r)) +PY +""" + + +def run(host, name): + print(f"\n===== {name} {host} =====", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=180) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:1200], flush=True) + c.close() + + +run("107.173.30.245", "dylive") +run("108.174.50.68", "dy") +print("DONE", flush=True) diff --git a/scripts/_cmp_studio_snaps.py b/scripts/_cmp_studio_snaps.py new file mode 100644 index 0000000..06ed87d --- /dev/null +++ b/scripts/_cmp_studio_snaps.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""Compare studio snaps for assign groups on both hosts.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, sys, json, asyncio +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app import yt_assign_db, youtube_neko +from app.youtube_relay_pipeline import youtube_relay_pipeline + +groups = yt_assign_db.list_groups(include_urls=False) +relay = youtube_relay_pipeline.status() +rows = {str(r.get("group_id") or ""): r for r in (relay.get("groups") or [])} +print("=== studio_snapshot_for_group ===") +for g in groups: + if not g.get("enabled"): + continue + name = g.get("name") + gid = g.get("id") + try: + snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=180.0) + except Exception as e: + print(name, "ERR", e) + continue + row = rows.get(str(gid) or "") or {} + print( + name, + "on_air", snap.get("on_air"), + "enc_recv", snap.get("encoder_receiving"), + "enc_lost", snap.get("encoder_lost"), + "status", snap.get("live_status"), + "src", snap.get("detect_source") or snap.get("source"), + "url", (snap.get("url") or "")[:55], + "pushing", row.get("is_pushing"), + "prefer", g.get("neko_open_prefer"), + ) +''' + + +def run(port, user, pwd, label, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + py = "/opt/douyinWEB/backend/.venv/bin/python -" + if sudo: + # write then sudo run + sftp = c.open_sftp() + with sftp.file("/tmp/_snap_cmp.py", "w") as f: + f.write(REMOTE) + sftp.close() + cmd = f"echo '{pwd}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_snap_cmp.py" + stdin, stdout, stderr = c.exec_command(cmd, timeout=120) + else: + stdin, stdout, stderr = c.exec_command(f"cd /opt/douyinWEB/backend && {py}", timeout=120) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-1200:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys", sudo=True) diff --git a/scripts/_cmp_yt_live_home.py b/scripts/_cmp_yt_live_home.py new file mode 100644 index 0000000..5a27d43 --- /dev/null +++ b/scripts/_cmp_yt_live_home.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare YouTube live counts on dy (physical) vs dylive (VPS).""" +from __future__ import annotations + +import json +import sys +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SITES = [ + ("dylive/VPS", "https://dylive.nomadro.com"), + ("dy/physical", "https://dy.nomadro.com"), +] + +PATHS = [ + "/api/health", + "/api/status", + "/api/youtube/status", + "/api/youtube/live", + "/api/youtube/assign/status", + "/api/youtube/relay/status", +] + + +def get(url: str, timeout: float = 12.0): + try: + req = urllib.request.Request(url, headers={"User-Agent": "dy-compare/1"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + body = r.read().decode("utf-8", "replace") + return r.status, body + except Exception as ex: + return 0, f"{type(ex).__name__}: {ex}" + + +def slim(path: str, body: str): + try: + d = json.loads(body) + except Exception: + return body[:200] + if path.endswith("/health"): + return { + k: d.get(k) + for k in ("ok", "host", "role", "host_profile", "version") + if k in d or True + } + if "youtube" in path and "relay" in path: + return { + "ok": d.get("ok"), + "pushing_count": d.get("pushing_count"), + "enabled": d.get("enabled") or d.get("pipeline_enabled"), + "groups_n": len(d.get("groups") or d.get("relay_groups") or []), + } + if "assign" in path: + return {k: d.get(k) for k in list(d)[:12]} + # generic pick live-ish keys + out = {} + for k in ( + "live_count", + "yt_live_count", + "youtube_live_count", + "active_sessions", + "ok", + "groups", + "overview", + "monitor", + "youtube", + ): + if k in d: + out[k] = d[k] + if "overview" in d and isinstance(d["overview"], dict): + out["overview"] = { + k: d["overview"].get(k) + for k in ("sessions", "active_sessions", "live", "live_count") + if k in d["overview"] + } + if not out: + # shallow scan + def walk(obj, prefix=""): + if isinstance(obj, dict): + for kk, vv in obj.items(): + lk = str(kk).lower() + if any(x in lk for x in ("live", "active", "session", "push")): + if not isinstance(vv, (dict, list)) or (isinstance(vv, list) and len(vv) < 5): + out[f"{prefix}{kk}"] = vv + if isinstance(vv, dict) and len(prefix) < 20: + walk(vv, prefix + kk + ".") + walk(d) + return out or {k: d.get(k) for k in list(d)[:8]} + + +def main(): + for name, base in SITES: + print(f"\n======== {name} {base} ========") + for p in PATHS: + code, body = get(base + p) + print(f"-- {p} [{code}]") + print(json.dumps(slim(p, body), ensure_ascii=False, indent=2)[:1200]) + + +if __name__ == "__main__": + main() diff --git a/scripts/_confirm_push_now.py b/scripts/_confirm_push_now.py new file mode 100644 index 0000000..f0e6013 --- /dev/null +++ b/scripts/_confirm_push_now.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Confirm ffmpeg still pushing + studio receiving.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + r""" +cd /opt/douyinWEB/backend +python3 - <<'PY' +import sqlite3, time, os, json +con=sqlite3.connect('data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +r=dict(con.execute('select * from yt_relay_states where group_id=?',(gid,)).fetchone() or {}) +pid=int(r.get('ffmpeg_pid') or 0) +alive=bool(pid and os.path.exists(f'/proc/{pid}')) +print('status', r.get('status'), 'error', (r.get('error') or '')[:120], 'pid', pid, 'alive', alive, 'push_sec', r.get('push_seconds'), 'age', round(time.time()-float(r.get('updated_at') or 0),1)) +log=str(r.get('recent_log') or '') +# show ffmpeg-ish tail lines if log is json array string +try: + lines=json.loads(log) if log.startswith('[') else log.splitlines() +except Exception: + lines=str(log).splitlines() +for ln in list(lines)[-12:]: + print('L', ln[:200] if isinstance(ln,str) else ln) +s=con.execute("select ts,on_air,live_status,health,viewer_count from yt_studio_samples where neko_ref='ops:1' order by ts desc limit 1").fetchone() +if s: + print('ops1', 'age', round(time.time()-float(s['ts']),1), 'on_air', s['on_air'], 'st', s['live_status'], 'health', s['health'], 'viewers', s['viewer_count']) +PY +# quick ps +ps -p 1870796 -o pid,etime,cmd 2>/dev/null | head -3 || echo 'pid gone' +""", + timeout=40, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_continue_dual_key_sync.py b/scripts/_continue_dual_key_sync.py new file mode 100644 index 0000000..31ff3b8 --- /dev/null +++ b/scripts/_continue_dual_key_sync.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Continue: sync key registry dy→dylive; apply jitless chrome restart on dylive neko-12; verify both.""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PASS = "Xiao4669805" +DY = "108.174.50.68" +DYLIVE = "107.173.30.245" + + +def connect(host: str, retries: int = 12): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail {host}: {last}") + + +def run(c, cmd: str, t: int = 180) -> str: + print(f"\n===== {cmd[:90].replace(chr(10),' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-10000:] if len(out) > 10000 else out, flush=True) + return out + + +# 1) export registry from dy +print("=== export dy registry ===", flush=True) +dy = connect(DY) +out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +print('EXPORT_JSON_START') +print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False)) +print('EXPORT_JSON_END') +print('neko:') +import subprocess +print(subprocess.check_output("docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'", shell=True).decode()) +PY +""", +) +dy.close() +start = out.find("EXPORT_JSON_START") +end = out.find("EXPORT_JSON_END") +assert start >= 0 and end > start, "no export" +payload = json.loads(out[start + len("EXPORT_JSON_START") : end].strip()) +items = payload.get("items") or [] +print(f"exported {len(items)} keys", flush=True) + +# 2) import to dylive + restart chrome with jitless on neko-12 only +print("=== dylive import + chrome restart ===", flush=True) +dl = connect(DYLIVE) +sftp = dl.open_sftp() +with sftp.file("/tmp/yt_stream_keys_from_dy.json", "w") as f: + f.write(json.dumps({"items": items}, ensure_ascii=False)) +sftp.close() + +run( + dl, + r""" +set +e +echo '=== before neko ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +free -h | head -2 + +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +data = json.load(open('/tmp/yt_stream_keys_from_dy.json', encoding='utf-8')) +print('peer_import', yt_stream_key_db.import_payload(data.get('items') or [], replace=False)) +print('local_assign_snap', yt_stream_key_db.import_from_assign_groups(replace=False)) +print('total', yt_stream_key_db.list_entries(include_secret=False)['total']) +# sample +for it in (yt_stream_key_db.list_entries(include_secret=True).get('items') or [])[:3]: + print('sample', it.get('name'), (it.get('stream_key') or '')[-4:]) +PY + +# ensure jitless on running neko chrome +if docker ps --format '{{.Names}}' | grep -qx douyinweb-neko-12; then + docker exec douyinweb-neko-12 grep -n jitless /etc/neko/browser-launch.sh | head -2 + docker exec douyinweb-neko-12 supervisorctl restart google-chrome + sleep 10 + docker exec douyinweb-neko-12 supervisorctl status google-chrome + docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "jitless|js-flags"; break;; + esac + done' +fi + +echo '=== after neko ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +systemctl is-active douyinweb-api douyinweb-web +""", +) +dl.close() + +# 3) public verify both +print("=== public verify ===", flush=True) +import ssl +import urllib.request +import http.cookiejar + +ctx = ssl.create_default_context() + + +def check(base: str): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=ctx), + ) + req = urllib.request.Request( + base + "/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + print(base, "login", op.open(req, timeout=30).status) + gs = json.loads(op.open(base + "/api/youtube/assign/groups", timeout=60).read()).get("groups") or [] + keys = json.loads(op.open(base + "/api/youtube/stream-keys", timeout=30).read()) + print( + base, + "groups", + len(gs), + "with_key", + sum(1 for g in gs if g.get("stream_key")), + "registry", + keys.get("total"), + "keys_page", + op.open(base + "/youtube/keys", timeout=30).status, + ) + + +check("https://dy.nomadro.live") +check("https://dylive.nomadro.com") +print("DONE") diff --git a/scripts/_continue_dy_oauth_long_check.py b/scripts/_continue_dy_oauth_long_check.py new file mode 100644 index 0000000..0f608b0 --- /dev/null +++ b/scripts/_continue_dy_oauth_long_check.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Follow-up: yt_long OAuth probe + neko/status + redirect URI reminder.""" +from __future__ import annotations + +import json +import sys +import urllib.parse +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +c = ssh() +_, o, _ = c.exec_command( + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +./.venv/bin/python - <<'PY' +import json, urllib.parse, urllib.request, urllib.error +from app import db, yt_long_db, yt_assign_db +from app import youtube_neko as yn + +def probe(label, cid, sec, rt): + rt = (rt or '').strip() + if not rt: + return {'label': label, 'ok': False, 'err': 'no_rt'} + data = urllib.parse.urlencode({ + 'client_id': (cid or '').strip(), + 'client_secret': (sec or '').strip(), + 'refresh_token': rt, + 'grant_type': 'refresh_token', + }).encode() + req = urllib.request.Request('https://oauth2.googleapis.com/token', data=data, method='POST') + try: + with urllib.request.urlopen(req, timeout=25) as r: + body = json.loads(r.read().decode()) + return {'label': label, 'ok': bool(body.get('access_token')), 'exp': body.get('expires_in')} + except Exception as e: + err = str(e) + if isinstance(e, urllib.error.HTTPError): + err = e.read().decode('utf-8','replace')[:180] + return {'label': label, 'ok': False, 'err': err} + +# yt_long +chs = [] +for name in ('list_channels', 'list_yt_long_channels', 'list_all'): + fn = getattr(yt_long_db, name, None) + if callable(fn): + try: + chs = fn() or [] + print('long_via', name, len(chs)) + break + except Exception as e: + print('long_fail', name, e) + +ok = bad = 0 +for ch in chs: + r = probe(f"long:{ch.get('name')}", ch.get('client_id'), ch.get('client_secret'), ch.get('refresh_token')) + print(json.dumps(r, ensure_ascii=False)) + ok += int(r['ok']); bad += int(not r['ok']) +print('long_summary', 'ok', ok, 'bad', bad, 'total', len(chs)) + +# assign oauth fields presence +groups = yt_assign_db.list_groups(include_urls=False) or [] +print('assign', len(groups)) +for g in groups: + print(json.dumps({ + 'name': g.get('name'), + 'neko': g.get('neko_instance_id'), + 'yt': (g.get('youtube_channel_id') or '')[:24], + 'has_rt': bool(str(g.get('refresh_token') or '').strip()), + 'prefer': g.get('neko_open_prefer'), + 'enabled': g.get('enabled'), + 'neko_enabled': g.get('neko_enabled'), + }, ensure_ascii=False)) + +# oauth client ids for console reminder +sm = db.get_settings_map() +print('redirect', sm.get('shorts_oauth_redirect_uri')) +profiles = sm.get('shorts_oauth_profiles') or [] +if isinstance(profiles, str): + profiles = json.loads(profiles) +for p in profiles: + if not isinstance(p, dict): + continue + cid = str(p.get('client_id') or '').strip() + if cid: + print('console_client', p.get('name') or p.get('id'), cid) + +# neko status +try: + snap = yn.list_instances() if hasattr(yn, 'list_instances') else None +except Exception: + snap = None +import subprocess +print(subprocess.check_output("docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'", shell=True).decode()) +print('mem'); print(subprocess.check_output('free -h', shell=True).decode()) +PY +""", + timeout=180, +) +print(o.read().decode("utf-8", "replace")) +c.close() diff --git a/scripts/_continue_dy_ops_harden.py b/scripts/_continue_dy_ops_harden.py new file mode 100644 index 0000000..765db16 --- /dev/null +++ b/scripts/_continue_dy_ops_harden.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python3 +"""Continue dy.nomadro.live ops harden: env/oauth/NAT, token probe, firewall persist, start assigned Nekos.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +PUBLIC = "https://dy.nomadro.live" +REDIRECT = f"{PUBLIC}/api/shorts/oauth/callback" +NAT = "108.174.50.68" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n===== {cmd[:120].replace(chr(10), ' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +c = ssh() + +# 1) Align public URL / redirect / NAT in env + settings +code, _ = run( + c, + rf""" +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +p = Path('/etc/douyinweb.env') +text = p.read_text(encoding='utf-8') if p.exists() else '' +kv = {{}} +lines = [] +for ln in text.splitlines(): + if '=' in ln and not ln.strip().startswith('#'): + k,v = ln.split('=',1) + kv[k.strip()] = v + lines.append(ln) + +want = {{ + 'DY_PUBLIC_BASE_URL': '{PUBLIC}', + 'PUBLIC_BASE': '{PUBLIC}', + 'DY_SITE_URL': '{PUBLIC}', + 'DY_NEKO_NAT1TO1': '{NAT}', + 'DY_NEKO_VPS_NAT1TO1': '{NAT}', +}} +changed = False +for k,v in want.items(): + if kv.get(k) != v: + kv[k] = v + changed = True + print('set', k, v) + else: + print('ok', k, v) +# rewrite file preserving unknown keys order roughly +out_lines = [] +seen = set() +for ln in lines: + if '=' in ln and not ln.strip().startswith('#'): + k = ln.split('=',1)[0].strip() + if k in want: + out_lines.append(f'{{k}}={{want[k]}}') + seen.add(k) + continue + out_lines.append(ln) +for k,v in want.items(): + if k not in seen: + out_lines.append(f'{{k}}={{v}}') + changed = True +if changed: + p.write_text('\\n'.join(out_lines) + '\\n', encoding='utf-8') + print('env_updated') +else: + print('env_unchanged') +PY + +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +./.venv/bin/python - <<'PY' +import json +from app import db +from app import config +sm = db.get_settings_map() +upd = {{}} +redir = '{REDIRECT}' +pub = '{PUBLIC}' +if str(sm.get('shorts_oauth_redirect_uri') or '').strip() != redir: + upd['shorts_oauth_redirect_uri'] = redir +# rewrite profiles redirect if present +profiles = sm.get('shorts_oauth_profiles') +if isinstance(profiles, str): + try: + profiles = json.loads(profiles) + except Exception: + profiles = None +if isinstance(profiles, list): + changed = False + for p in profiles: + if isinstance(p, dict) and str(p.get('redirect_uri') or '').strip() not in ('', redir): + p['redirect_uri'] = redir + changed = True + elif isinstance(p, dict) and not str(p.get('redirect_uri') or '').strip(): + p['redirect_uri'] = redir + changed = True + if changed or (isinstance(profiles, list) and profiles): + # always normalize stored profiles redirect + for p in profiles: + if isinstance(p, dict): + p['redirect_uri'] = redir + upd['shorts_oauth_profiles'] = profiles +if upd: + db.update_settings_map(upd) + print('settings_upd', list(upd.keys())) +else: + print('settings_ok') +print('cfg_public', getattr(config.settings, 'public_base_url', None) or getattr(config.settings, 'public_base', None)) +print('cfg_nat', getattr(config.settings, 'neko_nat1to1', None)) +print('redir', db.get_settings_map().get('shorts_oauth_redirect_uri')) +profiles = db.get_settings_map().get('shorts_oauth_profiles') +if isinstance(profiles, list): + for p in profiles: + cid = str(p.get('client_id') or '')[:28] + print('profile', p.get('name') or p.get('id'), cid+'…', 'redir', p.get('redirect_uri')) +PY +""", +) + +# 2) Persist firewall + check RAM before starting Nekos +code2, out2 = run( + c, + r""" +set -euo pipefail +# ensure rules +iptables -C INPUT -p udp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52000:52499 -j ACCEPT +iptables -C INPUT -p tcp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport 52000:52499 -j ACCEPT +iptables -C INPUT -p udp --dport 52300:52320 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52300:52320 -j ACCEPT +if command -v netfilter-persistent >/dev/null 2>&1; then + netfilter-persistent save || true + echo saved_netfilter +elif command -v iptables-save >/dev/null 2>&1; then + mkdir -p /etc/iptables + iptables-save > /etc/iptables/rules.v4 + echo saved_iptables_rules +else + echo no_persist_tool +fi +if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -qi active; then + ufw allow 52000:52499/udp || true + ufw allow 52000:52499/tcp || true + ufw allow 52300:52320/udp || true +fi +echo '--- mem ---' +free -h | head -3 +echo '--- units ---' +systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-s3 || true +""", +) + +# 3) Probe OAuth refresh tokens (shorts + assign via youtube client) +code3, _ = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +./.venv/bin/python - <<'PY' +import json, time +from app import db +from app import yt_assign_db +from app import yt_long_db + +try: + from app.youtube_client import refresh_access_token, get_channel_oauth_status +except Exception: + refresh_access_token = None + get_channel_oauth_status = None + +# discover helpers +import inspect +from app import youtube_client as yc +funcs = [n for n in dir(yc) if 'refresh' in n.lower() or 'oauth' in n.lower() or 'credential' in n.lower()] +print('yc_funcs', funcs[:40]) + +def try_refresh(label, client_id, client_secret, refresh_token): + cid = (client_id or '').strip() + sec = (client_secret or '').strip() + rt = (refresh_token or '').strip() + if not rt: + return {'label': label, 'ok': False, 'err': 'no_rt'} + # common patterns in this codebase + for name in ('refresh_access_token', 'exchange_refresh_token', 'fetch_access_token', 'token_from_refresh'): + fn = getattr(yc, name, None) + if callable(fn): + try: + out = fn(cid, sec, rt) if len(inspect.signature(fn).parameters) >= 3 else fn(rt) + if isinstance(out, dict): + ok = bool(out.get('access_token') or out.get('ok') or out.get('token')) + return {'label': label, 'ok': ok, 'via': name, 'err': (out.get('error') or out.get('err') or '')[:120]} + return {'label': label, 'ok': True, 'via': name} + except Exception as e: + return {'label': label, 'ok': False, 'via': name, 'err': str(e)[:160]} + # raw http + import urllib.request, urllib.parse + data = urllib.parse.urlencode({ + 'client_id': cid, + 'client_secret': sec, + 'refresh_token': rt, + 'grant_type': 'refresh_token', + }).encode() + req = urllib.request.Request('https://oauth2.googleapis.com/token', data=data, method='POST') + try: + with urllib.request.urlopen(req, timeout=25) as r: + body = json.loads(r.read().decode()) + return {'label': label, 'ok': bool(body.get('access_token')), 'via': 'http', 'exp': body.get('expires_in')} + except Exception as e: + err = str(e) + try: + import urllib.error + if isinstance(e, urllib.error.HTTPError): + err = e.read().decode('utf-8','replace')[:200] + except Exception: + pass + return {'label': label, 'ok': False, 'via': 'http', 'err': err[:200]} + +results = [] +for ch in db.list_shorts_channels() or []: + results.append(try_refresh( + f"shorts:{ch.get('name')}", + ch.get('client_id'), ch.get('client_secret'), ch.get('refresh_token'), + )) +for ch in (yt_long_db.list_channels() if hasattr(yt_long_db,'list_channels') else []) or []: + results.append(try_refresh( + f"long:{ch.get('name')}", + ch.get('client_id'), ch.get('client_secret'), ch.get('refresh_token'), + )) +# assign groups often store oauth on linked shorts / own fields +groups = yt_assign_db.list_groups(include_urls=False) or [] +for g in groups: + rt = g.get('refresh_token') or '' + if not rt: + continue + results.append(try_refresh( + f"assign:{g.get('name')}", + g.get('client_id'), g.get('client_secret'), rt, + )) + +ok_n = sum(1 for r in results if r.get('ok')) +bad = [r for r in results if not r.get('ok')] +print('oauth_probe_total', len(results), 'ok', ok_n, 'bad', len(bad)) +for r in results: + print(json.dumps(r, ensure_ascii=False)) +# unique neko slots from assign +slots = sorted({int(g.get('neko_instance_id') or 0) for g in groups if int(g.get('neko_instance_id') or 0) > 0}) +print('assign_neko_slots', slots) +PY +""", + t=240, +) + +# 4) Restart API if env changed, ensure capacity, start assigned neko slots (mem permitting) +code4, _ = run( + c, + r""" +set -euo pipefail +# reload env into API +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api + +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_NEKO_NAT1TO1=108.174.50.68 +./.venv/bin/python - <<'PY' +import json +from app import youtube_neko as yn +from app import yt_assign_db + +groups = yt_assign_db.list_groups(include_urls=False) or [] +slots = sorted({int(g.get('neko_instance_id') or 0) for g in groups if 1 <= int(g.get('neko_instance_id') or 0) <= 8}) +print('slots', slots) +# mem gate: need ~1.2G free per extra container roughly +import subprocess +mem = subprocess.check_output("free -b | awk '/Mem:/{print $7}'", shell=True).decode().strip() +avail = int(mem or 0) +print('mem_available_b', avail) +# always ensure compose/capacity for 8, but start only slots if mem ok +yn.ensure_capacity(8, start_instances=set(), reconcile_running=False) +# start assigned + keep 1 if already up; max concurrent starts based on avail +# keep 2GB headroom +budget = max(0, avail - 2_000_000_000) +max_start = max(1, min(len(slots) or 1, budget // 1_400_000_000)) +print('max_start', max_start) +to_start = set(slots[:max_start] if slots else [1]) +# if 1 running already include it +status = yn.status_snapshot() if hasattr(yn, 'status_snapshot') else None +print('to_start', sorted(to_start)) +# use docker start for reliability +import subprocess as sp +for i in sorted(to_start): + name = f'douyinweb-neko-{i}' + sp.run(['docker', 'start', name], check=False) +print('started_cmds_done') +PY +sleep 8 +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +curl -s http://127.0.0.1:8014/api/health | head -c 300; echo +curl -sk https://dy.nomadro.live/api/health | head -c 300; echo +curl -sk -o /dev/null -w 'neko1:%{http_code}\n' https://dy.nomadro.live/neko/1/ +""", + t=300, +) + +c.close() +print("\nALL_DONE", flush=True) diff --git a/scripts/_continue_dy_postinstall.py b/scripts/_continue_dy_postinstall.py new file mode 100644 index 0000000..eab3155 --- /dev/null +++ b/scripts/_continue_dy_postinstall.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Fix admin login + seed OAuth B + prepare Neko on dy.nomadro.live.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +ADMIN_USER = "hackrobot" +ADMIN_PASS = "Xiao4669805@" +REDIRECT = "https://dy.nomadro.live/api/shorts/oauth/callback" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return o.channel.recv_exit_status(), out + + +c = ssh() + +# 1) Force-reset admin to known password (env may not have matched hashed DB) +code, _ = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +# Match API process secrets +set -a +# shellcheck disable=SC1091 +source /etc/douyinweb.env +set +a +export DY_SESSION_SECRET="${SESSION_SECRET:-${DY_SESSION_SECRET:-}}" +export DY_ADMIN_USERNAME=hackrobot +export DY_ADMIN_PASSWORD='Xiao4669805@' +export DY_AUTH_ENABLED=true +./.venv/bin/python - <<'PY' +from app.session_auth import ( + ensure_default_admin_credentials, + verify_admin, + get_admin_credentials, + hash_password, + _secret, +) +from app import db, config + +want_user = "hackrobot" +want_pass = "Xiao4669805@" +print("secret_len", len(_secret())) +print("cfg_admin", config.settings.admin_username, "pass_len", len(str(config.settings.admin_password or ""))) +db.update_settings_map({ + "admin_username": want_user, + "admin_password_hash": hash_password(want_pass), +}) +ensure_default_admin_credentials() +# ensure_default may overwrite with settings.admin_password — force again after aligning env +db.update_settings_map({ + "admin_username": want_user, + "admin_password_hash": hash_password(want_pass), +}) +u, _h = get_admin_credentials() +print("admin_user", u) +print("verify", verify_admin(want_user, want_pass)) +PY + +# Also align systemd unit admin/session with known password +grep -q '^DY_ADMIN_PASSWORD=' /etc/douyinweb.env || true +# Ensure env file has DY_* aliases API/config expects +python3 - <<'PY' +from pathlib import Path +p = Path('/etc/douyinweb.env') +text = p.read_text(encoding='utf-8') +lines = text.splitlines() +kv = {} +for ln in lines: + if '=' in ln and not ln.strip().startswith('#'): + k,v = ln.split('=',1) + kv[k.strip()] = v +# keep SESSION_SECRET; expose DY_ aliases +sess = kv.get('DY_SESSION_SECRET') or kv.get('SESSION_SECRET') or '' +kv['SESSION_SECRET'] = sess +kv['DY_SESSION_SECRET'] = sess +kv['DY_ADMIN_USERNAME'] = 'hackrobot' +kv['DY_ADMIN_PASSWORD'] = 'Xiao4669805@' +kv['ADMIN_USER'] = 'hackrobot' +kv['DY_PUBLIC_BASE_URL'] = kv.get('DY_PUBLIC_BASE_URL') or kv.get('PUBLIC_BASE') or 'https://dy.nomadro.live' +out = [] +for k,v in kv.items(): + out.append(f'{k}={v}') +p.write_text('\n'.join(out)+'\n', encoding='utf-8') +print('env_updated', 'session_len', len(sess)) +PY +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 3 +curl -sS -o /tmp/login.json -w 'http:%{http_code}\n' -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/login.json; echo +""", +) +assert code == 0 + +# 2) Seed OAuth profile B from leftover client_secret JSON + redirect URI +code, _ = run( + c, + rf""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, glob +from pathlib import Path +from app import db +from app import shorts_oauth + +files = list(Path('/opt/douyinWEB').glob('client_secret_*.json')) +print('secret_files', [str(p.name) for p in files]) +assert files, 'missing client_secret json' +raw = json.loads(files[0].read_text(encoding='utf-8')) +web = raw.get('web') or raw.get('installed') or raw +cid = str(web.get('client_id') or '').strip() +sec = str(web.get('client_secret') or '').strip() +print('client_id', cid[:40]+'...') +assert cid and sec + +redirect = "{REDIRECT}" +profiles = shorts_oauth.normalize_oauth_profiles(db.get_settings_map().get('shorts_oauth_profiles')) +# merge B +out = [] +for p in profiles: + row = dict(p) + if row.get('id') == 'B': + row['client_id'] = cid + row['client_secret'] = sec + row['label'] = row.get('label') or '谷歌账号 B' + out.append(row) +db.update_settings_map({{ + 'shorts_oauth_profiles': out, + 'shorts_oauth_redirect_uri': redirect, + 'shorts_oauth_client_id': cid, # legacy fallback + 'shorts_oauth_client_secret': sec, +}}) +sm = db.get_settings_map() +print('redirect', sm.get('shorts_oauth_redirect_uri')) +for p in shorts_oauth.normalize_oauth_profiles(sm.get('shorts_oauth_profiles')): + print(p['id'], 'cid', (p.get('client_id') or '')[:28], 'sec', bool(p.get('client_secret'))) +PY +""", +) +assert code == 0 + +# 3) Ensure Neko compose capacity (create containers, do not start all) +code, _ = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +# create fleet definitions (no mass start) — capacity for assign later +print('docker', yn._docker_available()) +out = yn.ensure_capacity(4, start_instances=set(), reconcile_running=False) +print(out) +# list +for i in yn.list_instances(4, check_http=False): + print('neko', i.get('id'), i.get('status'), i.get('exists'), i.get('running')) +PY +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | head +""", + t=300, +) + +# 4) Public login page + API via domain +code, _ = run( + c, + r""" +set +e +curl -sS -o /dev/null -w 'pub_login:%{http_code}\n' --max-time 20 https://dy.nomadro.live/login +curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/login2.json -w 'pub_api_login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/login2.json; echo +curl -sS -b /tmp/dyj -o /dev/null -w 'me:%{http_code}\n' https://dy.nomadro.live/api/auth/me +""", +) + +c.close() +print("DONE") diff --git a/scripts/_continue_dy_wg_fix.py b/scripts/_continue_dy_wg_fix.py new file mode 100644 index 0000000..e8a5c77 --- /dev/null +++ b/scripts/_continue_dy_wg_fix.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Continue dy.nomadro.com recovery: try alt WG port, else Caddy via 10.9.0.2 if reachable. +No Neko. Live flush. +""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(port=22, user="root", pw="Xiao4669805"): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected :{port}", flush=True) + return c + except Exception as ex: + print(f"retry :{port} {i} {ex}", flush=True) + time.sleep(2) + raise RuntimeError("ssh fail") + + +def run(c, cmd, t=90): + print(f"$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## 1 inventory WG + caddy site", flush=True) +v = connect(22) +run( + v, + "ls -la /etc/wireguard/; " + "systemctl is-active 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null; " + "wg show; " + "ls /etc/caddy/sites/ | head -40; " + "grep -n 'reverse_proxy\\|dy.nomadro' /etc/caddy/sites/dy.nomadro.com.caddy 2>/dev/null | head -30 || " + "ls /etc/caddy/sites/dy* 2>/dev/null", +) +v.close() + +print("## 2 try ListenPort 443/udp for wg-dy (bypass common 51820 block)", flush=True) +v = connect(22) +run( + v, + "cp -a /etc/wireguard/wg-dy.conf /etc/wireguard/wg-dy.conf.bak.pre443; " + "sed -i 's/^ListenPort = .*/ListenPort = 443/' /etc/wireguard/wg-dy.conf; " + "grep -E 'ListenPort|Address|PublicKey|AllowedIPs' /etc/wireguard/wg-dy.conf; " + "ufw allow 443/udp comment 'wg-dy-alt' 2>/dev/null || true; " + "iptables -C INPUT -p udp --dport 443 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 443 -j ACCEPT; " + "wg-quick down wg-dy; wg-quick up wg-dy; " + "ss -ulnp | grep -E '443|51820' || true; " + "wg show wg-dy", +) +v.close() + +print("## 3 guest point Endpoint to :443", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "cp -a /etc/wireguard/wg-dy.conf /etc/wireguard/wg-dy.conf.bak.pre443; " + "sed -i \"s/^Endpoint = .*/Endpoint = 107.173.30.245:443/\" /etc/wireguard/wg-dy.conf; " + "grep -E \"Endpoint|Address|PublicKey|AllowedIPs|Keepalive\" /etc/wireguard/wg-dy.conf; " + "wg-quick down wg-dy; wg-quick up wg-dy; sleep 4; " + "wg show wg-dy; ping -c 4 -W 2 10.8.0.1 | tail -6" + "'", + t=50, +) +g.close() + +print("## 4 VPS check handshake", flush=True) +time.sleep(2) +v = connect(22) +run( + v, + "wg show wg-dy; ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 8 -o /dev/null -w via_wg=%{http_code}\\\\n http://10.8.0.2:8014/api/health", + t=30, +) +v.close() + +# If still dead, try Caddy via 10.9.0.2 through existing path +print("## 5 if still down, check reachability of 10.9.0.2 from VPS", flush=True) +v = connect(22) +run( + v, + "ping -c 2 -W 2 10.9.0.2 | tail -4; " + "curl -sS -m 5 -o /dev/null -w 'cn_api=%{http_code}\\\\n' http://10.9.0.2:8014/api/health; " + "ip route | grep -E '10\\.8\\.|10\\.9\\.' || true; " + "test -f /etc/wireguard/wg-dy-cn.conf && cat /etc/wireguard/wg-dy-cn.conf | sed -n '1,20p' || echo no_wg_dy_cn_conf", + t=25, +) +v.close() + +print("## public", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.cn/api/health", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_continue_dylive_mem_sigill.py b/scripts/_continue_dylive_mem_sigill.py new file mode 100644 index 0000000..1522ccb --- /dev/null +++ b/scripts/_continue_dylive_mem_sigill.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Continue dylive harden: pause non-project Docker, patch Chrome SIGILL in-place, verify.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +PASS = "Xiao4669805" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +STUDIO = "https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" + + +def connect(retries: int = 8): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail: {last}") + + +def run(c, cmd: str, t: int = 240) -> str: + print("\n=====", cmd[:90].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return out + + +text = LOCAL.read_text(encoding="utf-8") +assert "no-turbofan" in text +assert "PassageEmbeddings" in text + +c = connect() + +# 1) stop non-project containers +run( + c, + r""" +set +e +echo '=== before ===' +free -h | head -3 +docker ps --format '{{.Names}} {{.Status}}' | sort +for n in \ + nomadro-live-wp-wordpress-1 nomadro-live-wp-db-1 \ + nomadro-wp-wordpress-1 nomadro-wp-db-1 \ + deploy-nsqd-1 deploy-nsqadmin-1 deploy-nsqlookupd-1 \ + ntfy-ntfy-1 \ + umami-umami-1 umami-db-1 +do + case "$n" in douyinweb-*) continue ;; esac + docker stop "$n" 2>/dev/null && echo STOPPED "$n" || echo SKIP "$n" +done +# any other running non-douyinweb +while read -r name; do + case "$name" in + ''|douyinweb-*) continue ;; + *) docker stop "$name" 2>/dev/null && echo STOPPED "$name" ;; + esac +done < <(docker ps --format '{{.Names}}') +sync; echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true +echo '=== after stop ===' +docker ps --format '{{.Names}} {{.Status}}' | sort +free -h | head -3 +systemctl is-active sing-box frpp 'wg-quick@wg-dy' douyinweb-api douyinweb-web 2>/dev/null +""", +) + +# 2) patch browser-launch on the inode the container actually mounts +sftp = c.open_sftp() +tmp = "/tmp/browser-launch-sigill3.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) +sftp.close() + +run( + c, + rf""" +set -euo pipefail +CTR_INO=$(docker exec douyinweb-neko-12 sh -c "ls -li /etc/neko/browser-launch.sh" | awk '{{print $1}}') +echo CTR_INO=$CTR_INO +HOST_MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$CTR_INO" '$1==i {{print $NF; exit}}') +echo HOST_MATCH=$HOST_MATCH +# in-place overwrite mounted inode +if [ -n "$HOST_MATCH" ]; then + cat {tmp} > "$HOST_MATCH" +fi +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +docker exec douyinweb-neko-12 grep -n 'no-turbofan\|PassageEmbeddings\|renderer-process-limit' /etc/neko/browser-launch.sh +docker exec douyinweb-neko-12 supervisorctl restart google-chrome +sleep 14 +docker exec douyinweb-neko-12 supervisorctl status google-chrome +# chrome flags live? +docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "js-flags|turbofan|Passage|renderer-process|wasm"; break ;; + esac +done' +# close extra tabs, open one studio +docker exec douyinweb-neko-12 python3 -c ' +import json, urllib.request, time +S="{STUDIO}" +for i in range(40): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=2).read(); break + except Exception: + time.sleep(1) +else: + raise SystemExit("no_devtools") +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +kept=0 +for t in tabs: + if t.get("type")!="page": + continue + url=t.get("url") or "" + tid=t.get("id") or "" + # keep at most one studio livestreaming tab; close google/blank extras + if "studio.youtube.com" in url and "livestreaming" in url and kept==0: + kept=1 + try: urllib.request.urlopen("http://127.0.0.1:9222/json/activate/"+tid, timeout=3).read() + except Exception: pass + print("KEEP", url[:100]); continue + if tid: + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/close/"+tid, timeout=3).read() + print("CLOSE", url[:80]) + except Exception as e: + print("close_err", e) +if kept==0: + req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") + print("OPEN", urllib.request.urlopen(req, timeout=15).read()[:80]) +time.sleep(6) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print("TAB", (t.get("title") or "")[:60], "|", (t.get("url") or "")[:110]) +' +""", +) + +# 3) verify +run( + c, + r""" +set +e +echo '=== mem ===' +free -h | head -3 +echo '=== api cgroup ===' +systemctl show douyinweb-api -p MemoryCurrent,MemoryHigh,MemoryMax,OOMScoreAdjust +curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 280; echo +echo '=== docker running ===' +docker ps --format '{{.Names}} {{.Status}} {{.MemUsage}}' 2>/dev/null || docker ps --format '{{.Names}} {{.Status}}' +docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' | head -15 +echo '=== recent traps ===' +dmesg -T 2>/dev/null | grep -iE 'invalid opcode|oom-kill' | tail -6 +echo '=== untouchables ===' +systemctl is-active sing-box frpp 'wg-quick@wg-dy' +""", +) +c.close() +print("DONE") diff --git a/scripts/_continue_dylive_neko_pick.py b/scripts/_continue_dylive_neko_pick.py new file mode 100644 index 0000000..393d2f2 --- /dev/null +++ b/scripts/_continue_dylive_neko_pick.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Continue dylive recovery: status + start only the needed Neko (no recreate).""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print("ssh_retry", i, e, flush=True) + time.sleep(2) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=120): + print(f"\n$ {cmd[:110].replace(chr(10),' ')}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + out = (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + out = f"TIMEOUT {ex}" + print(out[-10000:] if len(out) > 10000 else out, flush=True) + return out + + +print("=== public smoke ===", flush=True) +try: + with urllib.request.urlopen("https://dylive.nomadro.com/youtube", timeout=20, context=CTX) as r: + print("youtube", r.status) +except Exception as e: + print("youtube FAIL", e) + +c = ssh() +run(c, "free -m | head -2; uptime; systemctl is-active douyinweb-api douyinweb-web caddy") +run( + c, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db, yt_assign_db +cfg = db.get_settings_map() +keys = [ + 'youtube_relay_enabled','youtube_relay_time_slot_mode','youtube_relay_exclusive_live', + 'youtube_relay_timeslot_test','youtube_relay_timeslot_test_group_id' +] +for k in keys: + print(f'{k}={cfg.get(k)}') +print('--- groups ---') +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if g.get('neko_enabled') or g.get('enabled'): + print( + f" {g.get('name')[:28]:28} cat={g.get('category')} neko={g.get('neko_instance_id')} " + f"neko_en={g.get('neko_enabled')} armed={g.get('time_slot_armed')} key={bool(g.get('has_stream_key'))}" + ) +PY +""", +) +run(c, "docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V") + +# Decide which neko to start: +# Prefer exclusive winner / timeslot active / neko_enabled=True; else none. +out = run( + c, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db, yt_assign_db +cfg = db.get_settings_map() +auto = bool(cfg.get('youtube_relay_enabled')) +slot = bool(cfg.get('youtube_relay_time_slot_mode')) +excl = bool(cfg.get('youtube_relay_exclusive_live', True)) +groups = yt_assign_db.list_groups(include_urls=False, include_secret=False) +# already enabled neko +enabled = [g for g in groups if g.get('neko_enabled') and int(g.get('neko_instance_id') or 0) > 0] +pick = None +if enabled: + pick = enabled[0] +elif slot and auto: + # current timeslot winner + try: + sch = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) + active = next((ch for ch in (sch.get('channels') or []) if ch.get('active')), None) + if active: + gid = str(active.get('group_id') or '') + pick = next((g for g in groups if str(g.get('id'))==gid), None) + except Exception as e: + print('sched_err', e) +# fallback: first normal with key if auto and not slot +if pick is None and auto and not slot: + for g in groups: + if str(g.get('category') or 'normal') != 'time_slot' and g.get('has_stream_key') and g.get('enabled'): + pick = g + break +if pick: + print(f"PICK id={pick.get('id')} name={pick.get('name')} neko={pick.get('neko_instance_id')} cat={pick.get('category')}") +else: + print('PICK none') +print(f'FLAGS auto={auto} slot={slot} excl={excl}') +PY +""", +) + +# parse PICK +neko_id = None +for line in out.splitlines(): + if line.startswith("PICK id=") and "neko=" in line: + try: + neko_id = int(line.split("neko=")[1].split()[0]) + except Exception: + pass + break + +if neko_id and neko_id > 0: + name = f"douyinweb-neko-{neko_id}" + print(f"\n=== start only {name} ===", flush=True) + run( + c, + f""" +set +e +# stop any other running nekos first (exclusive RAM) +for n in $(docker ps --format '{{{{.Names}}}}' | grep '^douyinweb-neko-' | grep -v '^{name}$'); do + echo stop $n; docker stop "$n" +done +docker start {name} || true +sleep 12 +docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort -V +docker exec {name} supervisorctl status 2>/dev/null | head -8 +docker exec {name} sh -c 'curl -sS -m 3 http://127.0.0.1:9222/json/version | head -c 100; echo' +free -m | head -2 +""", + t=180, + ) +else: + print("\n=== no neko pick — leave stopped ===", flush=True) + run(c, "free -m | head -2; docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V") + +# API login smoke +run( + c, + r""" +CS=$(mktemp) +curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' | head -c 100; echo +curl -sS -m 10 -b "$CS" -o /dev/null -w 'relay:%{http_code}\n' http://127.0.0.1:8014/api/youtube/relay/status +curl -sS -m 10 -o /dev/null -w 'fe:%{http_code}\n' http://127.0.0.1:4015/youtube +""", +) +c.close() +print("ALL_DONE") diff --git a/scripts/_continue_exclude_neko.py b/scripts/_continue_exclude_neko.py new file mode 100644 index 0000000..7fdea04 --- /dev/null +++ b/scripts/_continue_exclude_neko.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""Fix phys API if hung; deploy neko launch assets; import exclude; verify live.""" +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +LOCAL = Path(__file__).resolve().parents[1] +NEKO_FILES = [ + "backend/neko/browser-launch.sh", + "backend/neko/policies/policies.json", + "backend/neko/provisioning/tampermonkey-provisioning.json", + "backend/neko/provisioning/youtube-studio-auto-dismiss.user.js", +] + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put_files(c, sudo=None): + sftp = c.open_sftp() + for rel in NEKO_FILES: + tmp = f"/tmp/_nk_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((LOCAL / rel).read_bytes()) + dst = f"/opt/douyinWEB/{rel}" + if sudo: + run(c, f"echo '{sudo}' | sudo -S -p '' bash -lc \"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}; chmod +x {dst} 2>/dev/null || true\"", 30) + else: + run(c, f"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}; chmod +x {dst} 2>/dev/null || true", 20) + print("ok", rel) + sftp.close() + + +VERIFY = r''' +import json,urllib.request,http.cookiejar,time +for i in range(12): + try: + print("health", urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=3).status) + break + except Exception as e: + print("wait", i, type(e).__name__); time.sleep(2) +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req, timeout=15).status) +req=urllib.request.Request("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude/import-manual", data=json.dumps({"merge":True}).encode(), headers={"Content-Type":"application/json"}, method="POST") +imp=json.loads(op.open(req, timeout=60).read()) +print("import added", imp.get("added"), "count", imp.get("count")) +ex=json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=30).read()) +print("exclude count", ex.get("count"), "effective", ex.get("effective_room_count")) +try: + req=urllib.request.Request("http://127.0.0.1:8014/api/ops/neko/push-catalog", data=b"{}", headers={"Content-Type":"application/json"}, method="POST") + print("push", op.open(req, timeout=90).read()[:500]) +except Exception as e: + print("push", type(e).__name__, e) +lm=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=150).read()) +print("live_count", lm.get("live_count"), "source", lm.get("source")) +for k,v in sorted((lm.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", (v.get("title") or "")[:28], v.get("source")) +''' + + +def verify(c, sudo=None): + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_cont3.py", "w") as f: + f.write(VERIFY) + sftp.close() + print(run(c, f"echo '{sudo}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_cont3.py", 220)[:2500]) + else: + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -", timeout=220) + o.channel.sendall(VERIFY.encode()) + o.channel.shutdown_write() + print((o.read() + e.read()).decode("utf-8", "replace")[:2500]) + + +def main(): + # PHYS + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=30) + print("===== PHYS =====") + print(run(c, "echo '4669805' | sudo -S -p '' bash -lc 'systemctl is-active douyinweb-api; ss -lntp | grep 8014 || true'", 30)) + # bounce if health slow + print(run(c, "echo '4669805' | sudo -S -p '' systemctl restart douyinweb-api", 40)) + time.sleep(4) + put_files(c, "4669805") + verify(c, "4669805") + c.close() + + # VPS + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30) + print("===== VPS =====") + put_files(c) + verify(c) + c.close() + print("DONE") + + +if __name__ == "__main__": + main() diff --git a/scripts/_continue_frp_neko_ports.py b/scripts/_continue_frp_neko_ports.py new file mode 100644 index 0000000..757530c --- /dev/null +++ b/scripts/_continue_frp_neko_ports.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Continue: verify sites, try WG, else FRP-aux for Neko ports too. No Neko start.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def connect(port=22, user="root", pw="Xiao4669805"): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected :{port}", flush=True) + return c + except Exception as ex: + print(f"retry :{port} {i} {ex}", flush=True) + time.sleep(2) + raise RuntimeError("ssh fail") + + +def run(c, cmd, t=120): + print(f"$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## public now", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.cn/api/health", + "https://dy.nomadro.com/neko/1/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("## WG status + try reach 10.9.0.2", flush=True) +v = connect(22) +run( + v, + "systemctl is-active dy-frp-http-aux caddy douyinweb-api 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn'; " + "wg show; " + "ping -c 2 -W 2 10.8.0.2 | tail -3; " + "ping -c 2 -W 2 10.9.0.2 | tail -3; " + "curl -sS -m 5 -o /dev/null -w 'wg8=%{http_code} cn9=%{http_code}\\n' " + "http://10.8.0.2:8014/api/health http://10.9.0.2:8014/api/health 2>/dev/null || " + "curl -sS -m 5 -o /dev/null -w wg8=%{http_code}\\\\n http://10.8.0.2:8014/api/health; " + "curl -sS -m 5 -o /dev/null -w cn9=%{http_code}\\\\n http://10.9.0.2:8014/api/health; " + "cat /etc/wireguard/wg-dy-cn.conf", + t=40, +) +v.close() + +print("## extend FRP-aux to Neko 9200-9207 (still do NOT start containers)", flush=True) +v = connect(22) +run( + v, + r''' +set -e +# rebuild unit with api/web + neko 1..8 +FORWARDS="-L 127.0.0.1:18014:127.0.0.1:8014 -L 127.0.0.1:14015:127.0.0.1:4015" +for p in $(seq 9200 9207); do + FORWARDS="$FORWARDS -L 127.0.0.1:$p:127.0.0.1:$p" +done + +cat >/etc/systemd/system/dy-frp-http-aux.service < 127.0.0.1:920x in caddy site +SITE=/etc/caddy/sites/dy.nomadro.com.caddy +cp -a "$SITE" "$SITE.bak.nekofrp.$(date +%s)" +python3 - <<'PY' +from pathlib import Path +p = Path("/etc/caddy/sites/dy.nomadro.com.caddy") +t = p.read_text(encoding="utf-8") +n = 0 +for port in range(9200, 9208): + a = f"reverse_proxy 10.8.0.2:{port}" + b = f"reverse_proxy 127.0.0.1:{port}" + if a in t: + t = t.replace(a, b) + n += 1 +p.write_text(t, encoding="utf-8") +print("neko_proxy_rewrites", n) +PY +caddy validate --config /etc/caddy/Caddyfile >/tmp/caddyval.txt 2>&1 && echo caddy_ok || (tail -20 /tmp/caddyval.txt; exit 1) +systemctl reload caddy +systemctl is-active caddy +''', + t=90, +) +v.close() + +print("## public after", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/7/", + "https://dylive.nomadro.com/api/health", + "https://dy.nomadro.cn/api/health", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_continue_opsneko_harden.py b/scripts/_continue_opsneko_harden.py new file mode 100644 index 0000000..73e7591 --- /dev/null +++ b/scripts/_continue_opsneko_harden.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Continue: verify ops-neko chrome + edges; harden API env; deploy code both hosts.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +TENCENT = ("82.157.112.245", 22, "ubuntu", "Xiao4669805") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/ops_neko.py", + "backend/app/ops_neko_db.py", +] + + +def ssh(spec): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(spec[0], spec[1], spec[2], spec[3], timeout=45, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put_files(c, dest_root: str, *, sudo_user_pass: str | None = None): + sftp = c.open_sftp() + for rel in FILES: + data = (LOCAL / rel).read_bytes() + tmp = f"/tmp/_cont_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + dst = f"{dest_root}/{rel}" + if sudo_user_pass: + print( + run( + c, + f"echo '{sudo_user_pass}' | sudo -S -p '' bash -lc " + f"\"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"", + ), + end="", + ) + else: + print(run(c, f"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}"), end="") + print(f" -> {dst}", flush=True) + sftp.close() + + +def main(): + # --- physical verify + harden --- + p = ssh(PHYS) + print("=== PHYS status ===", flush=True) + print( + run( + p, + "echo '4669805' | sudo -S -p '' bash -lc '" + "docker exec douyinweb-ops-neko-1 supervisorctl status 2>/dev/null | head -10; " + "docker exec douyinweb-ops-neko-1 env | grep -E \"NAT1TO1|ENV_USER|BROWSER_PROXY\" | sort; " + "curl -sS -m 5 -o /dev/null -w \"ops_http=%{http_code}\\n\" http://127.0.0.1:18200/; " + "grep -E \"DY_NEKO_CN_NAT1TO1|DY_NEKO_VPS_NAT1TO1|DY_NEKO_NAT1TO1|DY_NEKO_HTTP_BIND\" " + " /etc/systemd/system/douyinweb-api.service | head -20; " + "'", + ), + flush=True, + ) + + print("=== PHYS deploy modules + soft restart API (keep containers) ===", flush=True) + put_files(p, "/opt/douyinWEB", sudo_user_pass="4669805") + print( + run( + p, + "echo '4669805' | sudo -S -p '' bash -lc '" + "SVC=/etc/systemd/system/douyinweb-api.service; " + "grep -q DY_NEKO_CN_NAT1TO1= \"$SVC\" || " + " sed -i \"/DY_NEKO_NAT1TO1=/a Environment=DY_NEKO_CN_NAT1TO1=82.157.112.245\" \"$SVC\"; " + "grep -q DY_NEKO_VPS_NAT1TO1= \"$SVC\" || " + " sed -i \"/DY_NEKO_NAT1TO1=/a Environment=DY_NEKO_VPS_NAT1TO1=107.173.30.245\" \"$SVC\"; " + "grep -q DY_NEKO_HTTP_BIND= \"$SVC\" || " + " sed -i \"/\\[Service\\]/a Environment=DY_NEKO_HTTP_BIND=0.0.0.0\" \"$SVC\"; " + "sed -i \"s|Environment=DY_NEKO_NAT1TO1=.*|Environment=DY_NEKO_NAT1TO1=82.157.112.245|\" \"$SVC\"; " + "systemctl daemon-reload; " + "systemctl restart douyinweb-api; " + "sleep 2; " + "systemctl is-active douyinweb-api; " + # ensure compose on disk still correct after code push + "export DY_NEKO_CN_NAT1TO1=82.157.112.245 DY_NEKO_VPS_NAT1TO1=107.173.30.245 " + " DY_NEKO_NAT1TO1=82.157.112.245 DY_NEKO_HTTP_BIND=0.0.0.0 DY_NEKO_EDGE_UPSTREAM=10.8.0.2; " + "cd /opt/douyinWEB/backend; " + "/opt/douyinWEB/backend/.venv/bin/python - <<\"PY\"\n" + "import os,sys\n" + "os.environ.setdefault(\"DY_NEKO_CN_NAT1TO1\",\"82.157.112.245\")\n" + "os.environ.setdefault(\"DY_NEKO_NAT1TO1\",\"82.157.112.245\")\n" + "os.environ.setdefault(\"DY_NEKO_HTTP_BIND\",\"0.0.0.0\")\n" + "os.environ.setdefault(\"DY_NEKO_EDGE_UPSTREAM\",\"10.8.0.2\")\n" + "sys.path.insert(0,\".\")\n" + "from app import ops_neko, ops_neko_db\n" + "ms=max(ops_neko_db.max_slot(),1)\n" + "t=ops_neko._render_compose(ms)\n" + "ops_neko._compose_path().write_text(t,encoding=\"utf-8\")\n" + "print(\"compose_ok\", \"ENV_USER\" in t, \"82.157\" in t, \"0.0.0.0:18200\" in t)\n" + "PY\n" + "docker exec douyinweb-ops-neko-1 supervisorctl status google-chrome || true; " + "'", + 180, + ), + flush=True, + ) + p.close() + + # --- VPS (dylive) deploy same modules (no recreate ops unless present) --- + v = ssh(VPS) + print("=== VPS deploy modules ===", flush=True) + put_files(v, "/opt/douyinWEB") + print( + run( + v, + "systemctl restart douyinweb-api 2>/dev/null || " + "systemctl restart dylive-api 2>/dev/null || true; " + "sleep 2; " + "systemctl is-active douyinweb-api 2>/dev/null; " + "systemctl is-active dylive-api 2>/dev/null; " + "curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "curl -sS -m 12 -o /dev/null -w 'dy_com=%{http_code}\\n' https://dy.nomadro.com/api/health; " + "curl -sS -m 12 -o /dev/null -w 'ops_com=%{http_code}\\n' https://dy.nomadro.com/ops-neko/1/; " + "systemctl is-active dy-frp-http-aux sing-box frpp 'wg-quick@wg-dy' | paste -sd' ' -", + 90, + ), + flush=True, + ) + v.close() + + # --- Tencent quick check --- + try: + t = ssh(TENCENT) + print("=== TENCENT ===", flush=True) + print( + run( + t, + "curl -sS -m 12 -o /dev/null -w 'cn_ops=%{http_code}\\n' https://dy.nomadro.cn/ops-neko/1/; " + "sudo iptables -t nat -S | grep OPS-NEKO | head -5; " + "nc -vz -w 2 10.9.0.2 18200 2>&1 | tail -1; " + "nc -vz -w 2 10.9.0.2 62300 2>&1 | tail -1", + 40, + ), + flush=True, + ) + t.close() + except Exception as exc: + print("tencent skip", exc, flush=True) + + print("DONE continue", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_continue_opsneko_persist.py b/scripts/_continue_opsneko_persist.py new file mode 100644 index 0000000..20a127c --- /dev/null +++ b/scripts/_continue_opsneko_persist.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Continue ops-neko: default .cn public base, persist Tencent DNAT, deploy frontend.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +TENCENT = ("82.157.112.245", 22, "ubuntu", "Xiao4669805") +LOCAL = Path(__file__).resolve().parents[1] +CN_BASE = "https://dy.nomadro.cn" + + +def ssh(spec): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(spec[0], spec[1], spec[2], spec[3], timeout=45, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=180): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +PERSIST_UNIT = r"""[Unit] +Description=ops-neko WebRTC DNAT (Tencent → physical via wg-dy-cn) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/ops-neko-webrtc-dnat.sh +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +""" + +DNAT_SH = r'''#!/bin/bash +set -u +COMMENT=OPS-NEKO-WEBRTC +TARGET=10.9.0.2 +WG_IF=wg-dy-cn +PUB_IF=$(ip route get 1.1.1.1 | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}') +[ -n "$PUB_IF" ] || exit 0 +sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true +while iptables-save -t nat 2>/dev/null | grep -q "$COMMENT"; do + line=$(iptables-save -t nat | grep "$COMMENT" | head -1 | sed 's/^-A /-D /') + iptables -t nat $line || break +done +while iptables-save 2>/dev/null | grep -q "$COMMENT"; do + line=$(iptables-save | grep "$COMMENT" | head -1 | sed 's/^-A /-D /') + iptables $line || break +done +add() { iptables "$@" >/dev/null 2>&1 || true; } +add -t nat -A PREROUTING -i "$PUB_IF" -p tcp --dport 62300:62307 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" +add -t nat -A PREROUTING -i "$PUB_IF" -p udp --dport 62300:62307 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" +add -t nat -A PREROUTING -i "$PUB_IF" -p udp --dport 62500:62579 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p tcp --dport 62300:62307 -m comment --comment "$COMMENT" -j MASQUERADE +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p udp --dport 62300:62307 -m comment --comment "$COMMENT" -j MASQUERADE +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p udp --dport 62500:62579 -m comment --comment "$COMMENT" -j MASQUERADE +command -v ufw >/dev/null 2>&1 && { + ufw allow 62300:62307/tcp >/dev/null 2>&1 || true + ufw allow 62300:62307/udp >/dev/null 2>&1 || true + ufw allow 62500:62579/udp >/dev/null 2>&1 || true +} +exit 0 +''' + + +def main(): + # 1) Tencent: persist DNAT + print("=== 1 Tencent persist DNAT ===", flush=True) + t = ssh(TENCENT) + sftp = t.open_sftp() + with sftp.file("/tmp/ops-neko-webrtc-dnat.sh", "w") as f: + f.write(DNAT_SH) + with sftp.file("/tmp/ops-neko-webrtc-dnat.service", "w") as f: + f.write(PERSIST_UNIT) + sftp.close() + print( + run( + t, + "sudo install -m 755 /tmp/ops-neko-webrtc-dnat.sh /usr/local/sbin/ops-neko-webrtc-dnat.sh; " + "sudo install -m 644 /tmp/ops-neko-webrtc-dnat.service /etc/systemd/system/ops-neko-webrtc-dnat.service; " + "sudo systemctl daemon-reload; " + "sudo systemctl enable --now ops-neko-webrtc-dnat.service; " + "systemctl is-enabled ops-neko-webrtc-dnat; " + "sudo iptables -t nat -S | grep OPS-NEKO | wc -l", + 60, + ), + flush=True, + ) + t.close() + + # 2) Physical: default ops_neko_public_base=.cn; deploy frontend page if buildable + print("=== 2 Physical public_base + frontend ===", flush=True) + p = ssh(PHYS) + # upload frontend neko page + shell nav if any + sftp = p.open_sftp() + for rel in ( + "frontend/src/app/neko/page.tsx", + "backend/app/ops_neko.py", + "backend/app/ops_neko_db.py", + "backend/app/youtube_neko.py", + ): + src = LOCAL / rel + if not src.is_file(): + continue + with sftp.file(f"/tmp/_c_{Path(rel).name}", "wb") as f: + f.write(src.read_bytes()) + print( + run( + p, + f"echo '4669805' | sudo -S -p '' bash -lc " + f"\"install -m 644 /tmp/_c_{Path(rel).name} /opt/douyinWEB/{rel}; " + f"sed -i 's/\\r$//' /opt/douyinWEB/{rel}\"", + ), + end="", + ) + print("ok", rel, flush=True) + sftp.close() + + print( + run( + p, + "echo '4669805' | sudo -S -p '' bash -lc '" + "cd /opt/douyinWEB/backend; " + "/opt/douyinWEB/backend/.venv/bin/python - <<\"PY\"\n" + "from app import ops_neko_db, db\n" + "st = ops_neko_db.peer_status()\n" + "pub = (st.get(\"public_base\") or \"\").strip()\n" + "if not pub:\n" + f" ops_neko_db.save_peer(public_base=\"{CN_BASE}\")\n" + f" print(\"set_public_base\", \"{CN_BASE}\")\n" + "else:\n" + " print(\"keep_public_base\", pub)\n" + "print(ops_neko_db.peer_status())\n" + "PY\n" + # rebuild frontend (may take a bit) + "cd /opt/douyinWEB/frontend; " + "if [ -f package.json ]; then " + " export NODE_ENV=production; " + " if command -v npm >/dev/null; then " + " npm run build >/tmp/neko_fe_build.log 2>&1 && echo FE_BUILD_OK || (echo FE_BUILD_FAIL; tail -30 /tmp/neko_fe_build.log); " + " systemctl restart douyinweb-web 2>/dev/null || true; " + " systemctl is-active douyinweb-web; " + " else echo no_npm; fi; " + "else echo no_frontend; fi; " + "docker exec douyinweb-ops-neko-1 supervisorctl status google-chrome; " + "systemctl is-active douyinweb-api; " + "'", + 600, + ), + flush=True, + ) + p.close() + + # 3) Final health + print("=== 3 health ===", flush=True) + v = ssh(VPS) + print( + run( + v, + "curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "curl -sS -m 15 -o /dev/null -w 'dy=%{http_code}\\n' https://dy.nomadro.com/api/health; " + "curl -sS -m 15 -o /dev/null -w 'ops_com=%{http_code}\\n' https://dy.nomadro.com/ops-neko/1/; " + "curl -sS -m 15 -o /dev/null -w 'ops_cn=%{http_code}\\n' https://dy.nomadro.cn/ops-neko/1/; " + "systemctl is-active dy-frp-http-aux sing-box frpp 'wg-quick@wg-dy'", + 90, + ), + flush=True, + ) + v.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_continue_quota_and_ga.py b/scripts/_continue_quota_and_ga.py new file mode 100644 index 0000000..6dc9c99 --- /dev/null +++ b/scripts/_continue_quota_and_ga.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Verify yt-long quota persist + start qemu-guest-agent (no reboot/neko).""" +from __future__ import annotations + +import json +import sys +import urllib.request +import http.cookiejar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def api_check(base: str, label: str) -> None: + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + req = urllib.request.Request( + base + "/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + print(label, "login", op.open(req, timeout=25).status, flush=True) + # set 7 + req2 = urllib.request.Request( + base + "/api/yt-long/settings", + data=json.dumps({"yt_long_channel_daily_max": 7, "apply_channel_daily_max": True, "enabled_only": True}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + r = json.loads(op.open(req2, timeout=45).read()) + print( + label, + "apply", + "settings=", + r.get("settings", {}).get("yt_long_channel_daily_max"), + "top=", + r.get("channel_daily_max"), + "quota_apply=", + r.get("quota_apply"), + flush=True, + ) + st = json.loads(op.open(base + "/api/yt-long/status", timeout=45).read()) + print( + label, + "status", + st.get("settings", {}).get("yt_long_channel_daily_max"), + "top", + st.get("channel_daily_max"), + flush=True, + ) + # board channel sample + chans = (st.get("board") or {}).get("channels") or [] + if not chans: + # try channels list endpoint if any + try: + cl = json.loads(op.open(base + "/api/yt-long/channels", timeout=30).read()) + chans = cl.get("channels") or [] + except Exception as e: + print(label, "channels_err", e, flush=True) + sample = [ + {"name": c.get("name"), "daily_max": c.get("daily_max"), "enabled": c.get("enabled")} + for c in chans[:5] + ] + print(label, "channels_sample", sample, flush=True) + + +AGENT = r"""#!/bin/bash +set -e +echo '=== before ===' +free -h | head -2 +grep MemTotal /proc/meminfo +systemctl is-active qemu-guest-agent 2>/dev/null || true +if ! dpkg -l qemu-guest-agent 2>/dev/null | grep -q '^ii'; then + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq + apt-get install -y -qq qemu-guest-agent +fi +systemctl enable --now qemu-guest-agent +sleep 1 +systemctl is-active qemu-guest-agent +echo '=== after mem ===' +free -h | head -2 +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo +""" + + +def phys_agent() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_ga_start.sh", "w") as f: + f.write(AGENT) + sftp.close() + print("===== PHYS guest-agent =====", flush=True) + _, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_ga_start.sh", timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +def main() -> int: + for base, label in ( + ("https://dy.nomadro.com", "dy"), + ("https://dylive.nomadro.com", "dylive"), + ): + try: + api_check(base, label) + except Exception as ex: + print(label, "ERR", ex, flush=True) + print("---", flush=True) + phys_agent() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_copy_phys_channels_to_dylive.py b/scripts/_copy_phys_channels_to_dylive.py new file mode 100644 index 0000000..5ddc652 --- /dev/null +++ b/scripts/_copy_phys_channels_to_dylive.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Copy Douyin rooms + YouTube channel tables from physical → dylive VPS.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +GUEST_SUDO = "4669805" +DB = "/opt/douyinWEB/backend/data/monitor.db" +TS = time.strftime("%Y%m%d_%H%M%S") + +CHANNEL_TABLES = [ + "rooms", + "blacklist", + "channel_groups", + "shorts_channels", + "yt_long_channels", + "yt_assign_groups", + "yt_assign_pool_urls", + "yt_assign_featured_urls", + "yt_assign_slot_urls", +] + +KV_KEYS = [ + "shorts_oauth_profiles", + "cookie", + "douyin_cookie", + "monitor_cookie", + "web_cookie", +] + +PHYS_SNAP_PY = f""" +import sqlite3 +src = sqlite3.connect("{DB}") +dst = sqlite3.connect("/tmp/phys_monitor_for_dylive.db") +src.backup(dst) +dst.close() +src.close() +c = sqlite3.connect("/tmp/phys_monitor_for_dylive.db") +tables = {CHANNEL_TABLES!r} +for t in tables: + try: + n = c.execute(f"select count(*) from [{{t}}]").fetchone()[0] + except Exception as e: + n = str(e) + print(t, n) +c.close() +print("SNAP_OK") +""" + +MERGE_PY = f""" +import json +import sqlite3 +from pathlib import Path + +SRC = Path("/tmp/phys_monitor_for_dylive.db") +DST = Path("{DB}") +TABLES = {CHANNEL_TABLES!r} +KV_KEYS = {KV_KEYS!r} + +assert SRC.is_file(), f"missing src {{SRC}}" +assert DST.is_file(), f"missing dst {{DST}}" + +src = sqlite3.connect(str(SRC)) +dst = sqlite3.connect(str(DST)) +src.row_factory = sqlite3.Row +dst.row_factory = sqlite3.Row + +def cols(con, table): + return [r[1] for r in con.execute(f"PRAGMA table_info([{{table}}])").fetchall()] + +def table_exists(con, table): + return bool(con.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,) + ).fetchone()) + +report = {{"tables": {{}}, "kv": {{}}}} + +for t in TABLES: + if not table_exists(src, t): + report["tables"][t] = {{"skipped": "missing_on_physical"}} + continue + if not table_exists(dst, t): + schema = src.execute( + "SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,) + ).fetchone() + if schema and schema[0]: + dst.execute(schema[0]) + dst.commit() + else: + report["tables"][t] = {{"skipped": "no_schema"}} + continue + sc = cols(src, t) + dc = cols(dst, t) + common = [c for c in sc if c in dc] + if not common: + report["tables"][t] = {{"skipped": "no_common_cols"}} + continue + before = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] + dst.execute(f"DELETE FROM [{{t}}]") + rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall() + if rows: + qcols = ",".join(f"[{{c}}]" for c in common) + placeholders = ",".join("?" for _ in common) + sql = f"INSERT INTO [{{t}}] ({{qcols}}) VALUES ({{placeholders}})" + payload = [] + for r in rows: + d = dict(r) + payload.append(tuple(d.get(c) for c in common)) + dst.executemany(sql, payload) + after = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] + report["tables"][t] = {{ + "before": before, + "copied": len(rows), + "after": after, + "cols": len(common), + }} + +if table_exists(src, "kv_settings") and table_exists(dst, "kv_settings"): + for key in KV_KEYS: + row = src.execute("SELECT value FROM kv_settings WHERE key=?", (key,)).fetchone() + if not row: + report["kv"][key] = "absent_on_physical" + continue + dst.execute( + "INSERT INTO kv_settings(key, value) VALUES(?, ?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + (key, row[0]), + ) + report["kv"][key] = "copied" + +if table_exists(dst, "yt_assign_groups"): + gcols = set(cols(dst, "yt_assign_groups")) + if "neko_enabled" in gcols: + cur = dst.execute("UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0") + report["neko_disabled"] = cur.rowcount + +dst.commit() +src.close() +dst.close() +print(json.dumps(report, ensure_ascii=False, indent=2)) +print("MERGE_OK") +""" + +COUNT_PY = f""" +import sqlite3 +c = sqlite3.connect("{DB}") +for t in {CHANNEL_TABLES!r}: + try: + n = c.execute(f"select count(*) from [{{t}}]").fetchone()[0] + except Exception as e: + n = str(e) + print(t, n) +try: + ne = c.execute("select count(*) from yt_assign_groups where neko_enabled=1").fetchone()[0] +except Exception: + ne = "n/a" +print("neko_enabled_on", ne) +c.close() +""" + + +def connect(host, port, user, password): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, port, user, password, + timeout=60, banner_timeout=120, + allow_agent=False, look_for_keys=False, + ) + return c + + +def run(c, cmd, timeout=300): + print(f"\n$ {cmd[:240]}{'…' if len(cmd) > 240 else ''}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-10000:] if len(out) > 10000 else out, flush=True) + print(f"→ exit={code}", flush=True) + return code, out + + +def sftp_put(c, data: bytes, remote: str): + sftp = c.open_sftp() + try: + with sftp.open(remote, "wb") as f: + f.write(data) + finally: + sftp.close() + + +def sftp_get(c, remote: str) -> bytes: + sftp = c.open_sftp() + try: + with sftp.open(remote, "rb") as f: + return f.read() + finally: + sftp.close() + + +def main() -> int: + print(f"=== physical channels → dylive ts={TS} ===", flush=True) + + # 1) physical snapshot + p = connect(*PHYS) + try: + sftp_put(p, PHYS_SNAP_PY.encode("utf-8"), "/tmp/phys_snap_channels.py") + code, out = run( + p, + f"echo '{GUEST_SUDO}' | sudo -S -p '' bash -lc '" + f"python3 /tmp/phys_snap_channels.py && " + f"chown eric:eric /tmp/phys_monitor_for_dylive.db && " + f"ls -lh /tmp/phys_monitor_for_dylive.db" + f"'", + timeout=120, + ) + if code != 0 or "SNAP_OK" not in out: + print("FATAL: physical snapshot failed", flush=True) + return 1 + blob = sftp_get(p, "/tmp/phys_monitor_for_dylive.db") + print(f"downloaded bytes={len(blob)}", flush=True) + finally: + p.close() + + # 2) VPS backup + merge + v = connect(*VPS) + try: + bak = f"/root/dylive_bak_before_phys_channels_{TS}" + code, _ = run( + v, + f"set -e; mkdir -p {bak}; " + f"cp -a {DB} {bak}/monitor.db; " + f"cp -a {DB}-wal {bak}/ 2>/dev/null || true; " + f"cp -a {DB}-shm {bak}/ 2>/dev/null || true; " + f"cp -a /etc/douyinweb.env {bak}/douyinweb.env 2>/dev/null || true; " + f"cp -a /etc/systemd/system/douyinweb-api.service {bak}/ 2>/dev/null || true; " + f"cp -a /etc/systemd/system/douyinweb-web.service {bak}/ 2>/dev/null || true; " + f"systemctl cat douyinweb-api > {bak}/douyinweb-api.service.cat 2>/dev/null || true; " + f"ls -lah {bak}", + timeout=90, + ) + if code != 0: + print("FATAL: backup failed", flush=True) + return 1 + + print("\n--- VPS counts BEFORE ---", flush=True) + sftp_put(v, COUNT_PY.encode("utf-8"), "/tmp/count_channels.py") + run(v, "python3 /tmp/count_channels.py", timeout=60) + + sftp_put(v, blob, "/tmp/phys_monitor_for_dylive.db") + sftp_put(v, MERGE_PY.encode("utf-8"), f"/tmp/merge_phys_channels_{TS}.py") + + run(v, "systemctl stop douyinweb-api; sleep 2; systemctl is-active douyinweb-api || true", 60) + code, out = run(v, f"python3 /tmp/merge_phys_channels_{TS}.py", 180) + if code != 0 or "MERGE_OK" not in out: + print("FATAL: merge failed, restoring", flush=True) + run( + v, + f"cp -a {bak}/monitor.db {DB}; systemctl start douyinweb-api; sleep 2; systemctl is-active douyinweb-api", + 60, + ) + return 1 + + run( + v, + "systemctl start douyinweb-api; sleep 3; systemctl is-active douyinweb-api", + 60, + ) + print("\n--- VPS counts AFTER ---", flush=True) + run(v, "python3 /tmp/count_channels.py", 60) + run( + v, + "curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "curl -sS -m 15 -o /dev/null -w 'dy_com=%{http_code}\\n' https://dy.nomadro.com/api/health", + 40, + ) + print(f"\nOK backup_dir={bak}", flush=True) + return 0 + finally: + v.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_copy_phys_kv_oauth_to_dylive.py b/scripts/_copy_phys_kv_oauth_to_dylive.py new file mode 100644 index 0000000..8c71299 --- /dev/null +++ b/scripts/_copy_phys_kv_oauth_to_dylive.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Copy remaining Douyin cookie / OAuth kv keys from physical → dylive (post channel sync).""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +GUEST_SUDO = "4669805" +DB = "/opt/douyinWEB/backend/data/monitor.db" +TS = time.strftime("%Y%m%d_%H%M%S") + +KEYS = [ + "dy_cookie", + "dy_cookie_updated_at", + "shorts_oauth_profiles", + "shorts_oauth_client_id", + "shorts_oauth_client_secret", + "shorts_oauth_redirect_uri", + "shorts_oauth_brand_hints", + "yt_studio_cookies_by_profile", +] + +EXPORT_PY = f""" +import json, sqlite3 +c = sqlite3.connect("{DB}") +out = {{}} +for k in {KEYS!r}: + row = c.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone() + if row: + out[k] = row[0] + print("has", k, "len", len(row[0] or "")) + else: + print("miss", k) +c.close() +open("/tmp/phys_kv_oauth.json","w",encoding="utf-8").write(json.dumps(out, ensure_ascii=False)) +print("EXPORT_OK", len(out)) +""" + +IMPORT_PY = f""" +import json, sqlite3, shutil, time +from pathlib import Path +bak = Path("/root/dylive_bak_kv_oauth_{TS}") +bak.mkdir(parents=True, exist_ok=True) +shutil.copy2("{DB}", bak / "monitor.db") +data = json.loads(Path("/tmp/phys_kv_oauth.json").read_text(encoding="utf-8")) +c = sqlite3.connect("{DB}") +for k, v in data.items(): + c.execute( + "INSERT INTO kv_settings(key, value) VALUES(?, ?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + (k, v), + ) + print("set", k, "len", len(v or "")) +c.commit() +c.close() +print("IMPORT_OK", "bak", str(bak)) +""" + + +def connect(spec): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*spec, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, timeout=120): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-5000:] if len(out) > 5000 else out, flush=True) + print(f"→ exit={code}", flush=True) + return code, out + + +def sftp_put(c, data: bytes, remote: str): + sftp = c.open_sftp() + try: + with sftp.open(remote, "wb") as f: + f.write(data) + finally: + sftp.close() + + +def sftp_get(c, remote: str) -> bytes: + sftp = c.open_sftp() + try: + with sftp.open(remote, "rb") as f: + return f.read() + finally: + sftp.close() + + +def main() -> int: + p = connect(PHYS) + try: + sftp_put(p, EXPORT_PY.encode("utf-8"), "/tmp/export_phys_kv.py") + code, out = run( + p, + f"echo '{GUEST_SUDO}' | sudo -S -p '' bash -lc 'python3 /tmp/export_phys_kv.py && chown eric:eric /tmp/phys_kv_oauth.json'", + ) + if code != 0 or "EXPORT_OK" not in out: + return 1 + blob = sftp_get(p, "/tmp/phys_kv_oauth.json") + finally: + p.close() + + v = connect(VPS) + try: + sftp_put(v, blob, "/tmp/phys_kv_oauth.json") + sftp_put(v, IMPORT_PY.encode("utf-8"), "/tmp/import_phys_kv.py") + run(v, "systemctl stop douyinweb-api; sleep 1", 40) + code, out = run(v, "python3 /tmp/import_phys_kv.py", 60) + run(v, "systemctl start douyinweb-api; sleep 2; systemctl is-active douyinweb-api; " + "curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health", 40) + return 0 if code == 0 and "IMPORT_OK" in out else 1 + finally: + v.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_dbg_phys_two_live.py b/scripts/_dbg_phys_two_live.py new file mode 100644 index 0000000..916ee00 --- /dev/null +++ b/scripts/_dbg_phys_two_live.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import asyncio, os, sys, json +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live, yt_assign_db, youtube_neko, youtube_client, db + +GIDS = [ + "e9bae7e8-ea13-4cf0-a96c-757069d662df", + "adeca103-800a-4cfb-b8eb-55375fe39fbc", +] + +async def main(): + youtube_live._LAST_OAUTH_AT = 0.0 + # Direct probes + for gid in GIDS: + g = yt_assign_db.get_group(gid) or {} + cid = str(g.get("youtube_channel_id") or "") + pk = str(g.get("channel_pk") or "") + print("GROUP", g.get("name"), "cid", cid, "pk", pk) + url = f"https://www.youtube.com/channel/{cid}" + try: + bl = await youtube_client.batch_live([url]) + r = (bl.get("results") or [{}])[0] + print(" youtubei", "is_live", r.get("is_live"), "err", r.get("error"), "src ok") + except Exception as ex: + print(" youtubei_err", ex) + try: + oa = await youtube_live._oauth_live_for_shorts(pk, cid) + print(" oauth", oa) + except Exception as ex: + print(" oauth_err", ex) + snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=180) + print(" studio", {k: snap.get(k) for k in ("on_air","encoder_receiving","encoder_lost","live_status","session_live","neko_ref","age_sec","detect_source")}) + + m = await youtube_live.build_live_map(force=True) + for gid in GIDS: + e = (m.get("entries") or {}).get(f"assign:{gid}") or {} + g = yt_assign_db.get_group(gid) or {} + cid = str(g.get("youtube_channel_id") or "") + pk = str(g.get("channel_pk") or "") + print("ENTRY assign", gid[:8], "is_live", e.get("is_live"), "source", e.get("source"), "err", e.get("error")) + print(" channel", (m.get("entries") or {}).get(f"channel:{cid}")) + print(" shorts", (m.get("entries") or {}).get(f"shorts:{pk}")) + print("live_count", m.get("live_count")) + +asyncio.run(main()) +''' + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dbg_phys_two.py", "w") as f: + f.write(REMOTE) + sftp.close() + cmd = "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_dbg_phys_two.py" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")[:5000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_dbg_youtubei_batch.py b/scripts/_dbg_youtubei_batch.py new file mode 100644 index 0000000..5622c51 --- /dev/null +++ b/scripts/_dbg_youtubei_batch.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Debug youtubei batch_live for assign UC ids on both hosts.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app import youtube_client +from app.config import settings + +URLS = [ + "https://www.youtube.com/channel/UCXFErW9DeE8EXrInlnyCnVw", # asian streetfood (phys live?) + "https://www.youtube.com/channel/UCYnwXkCMmVFf8Vr6MlWb-Jw", # hackrobotlite + "https://www.youtube.com/channel/UCjQ8jnBm2N4FGRowNXcXThw", # asian streetfood timeslot +] + +async def main(): + print("DY_YOUTUBE_SVC_URL", getattr(settings, "youtube_svc_url", None)) + try: + print("health", await youtube_client.health()) + except Exception as ex: + print("health_err", ex) + try: + data = await youtube_client.batch_live(URLS) + print("ok", data.get("ok"), "n", len(data.get("results") or [])) + for r in data.get("results") or []: + live = r.get("live") if isinstance(r.get("live"), dict) else {} + print( + " is_live=", r.get("is_live"), + "cid=", r.get("channel_id"), + "err=", str(r.get("error") or "")[:80], + "title=", str(live.get("title") or r.get("title") or "")[:40], + "url=", str(live.get("url") or "")[:60], + "input=", str(r.get("input") or "")[-40:], + ) + except Exception as ex: + print("batch_err", type(ex).__name__, ex) + # single + try: + one = await youtube_client.channel_live(URLS[0]) + print("channel_live0", one) + except Exception as ex: + print("channel_live_err", type(ex).__name__, ex) + +asyncio.run(main()) +''' + + +def one(label, host, port, user, pw, sudo=False): + print(f"\n##### {label} #####") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dbg_yt.py", "w") as f: + f.write(REMOTE) + sftp.close() + # also show unit / curl + extra = ( + "systemctl is-active douyinweb-yt; " + "systemctl show douyinweb-yt -p Environment -p ExecStart --no-pager | head -5; " + "curl -sS -m 3 http://127.0.0.1:3100/health 2>/dev/null | head -c 120; echo; " + "curl -sS -m 3 http://127.0.0.1:3001/health 2>/dev/null | head -c 120; echo; " + "ss -lntp | grep -E '3100|3001|8099|4015' | head; " + "grep -E 'YOUTUBE_SVC|youtube_svc' /opt/douyinWEB/backend/.env /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -20" + ) + cmd = f"bash -lc '{extra}'" + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc \"{extra}\"" + _, o, e = c.exec_command(cmd, timeout=30) + print((o.read() + e.read()).decode("utf-8", "replace")[:1500]) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_dbg_yt.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + _, o, e = c.exec_command(py, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")[:3000]) + c.close() + + +def main(): + one("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) + one("PHYS", "107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_dedupe_dylive_registry.py b/scripts/_dedupe_dylive_registry.py new file mode 100644 index 0000000..c5bc9e7 --- /dev/null +++ b/scripts/_dedupe_dylive_registry.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Replace dylive key registry with dy export (dedupe); re-verify both.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +APP_PASS = "Xiao4669805@" +SSH_PASS = "Xiao4669805" + + +def ssh(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + SSH_PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, cmd: str, t: int = 120) -> str: + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def http_check(label: str, base: str): + cj = CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": APP_PASS}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + op.open(req, timeout=45).read() + with op.open(f"{base}/api/youtube/stream-keys", timeout=45) as r: + sk = json.loads(r.read().decode()) + with op.open(f"{base}/api/youtube/assign/groups", timeout=45) as r: + ag = json.loads(r.read().decode()) + groups = ag.get("groups") or [] + full = sum(1 for g in groups if len(str(g.get("stream_key") or "")) >= 12) + names = [(g.get("name") or g.get("id")) for g in groups] + print( + f"{label}: registry={sk.get('total')} assign={len(groups)} full_keys={full}", + flush=True, + ) + missing = [g.get("name") for g in groups if len(str(g.get("stream_key") or "")) < 12] + if missing: + print(f" missing keys: {missing}") + return set(str(n) for n in names if n) + + +print("export dy…", flush=True) +dy = ssh("108.174.50.68") +out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +print('REG_START') +print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False)) +print('REG_END') +PY +""", +) +dy.close() +a, b = out.find("REG_START"), out.find("REG_END") +reg = json.loads(out[a + len("REG_START") : b].strip()) +items = reg.get("items") or [] +print(f"dy registry items={len(items)}", flush=True) + +dl = ssh("107.173.30.245") +sftp = dl.open_sftp() +with sftp.file("/tmp/dy_stream_key_export.json", "w") as f: + f.write(json.dumps(reg, ensure_ascii=False)) +sftp.close() +print( + run( + dl, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +with open('/tmp/dy_stream_key_export.json', encoding='utf-8') as f: + reg = json.load(f) +items = reg.get('items') or [] +print(yt_stream_key_db.import_payload(items, replace=True)) +print(yt_stream_key_db.list_entries(include_secret=False)['total']) +PY +""", + ), + flush=True, +) +dl.close() + +print("\nverify HTTP:", flush=True) +dy_names = http_check("dy", "https://dy.nomadro.live") +dl_names = http_check("dylive", "https://dylive.nomadro.com") +print("only_on_dy:", sorted(dy_names - dl_names)) +print("only_on_dylive:", sorted(dl_names - dy_names)) +print("DONE") diff --git a/scripts/_deep_why_push_idle.py b/scripts/_deep_why_push_idle.py new file mode 100644 index 0000000..403cb0c --- /dev/null +++ b/scripts/_deep_why_push_idle.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deep dive why push dies / idle after start.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + r""" +# journal for relay/ffmpeg errors +journalctl -u douyinweb-api --since '15 min ago' --no-pager 2>/dev/null | grep -iE 'relay|ffmpeg|invalid|neko wait|blocked|NODATA|on_air|3fb8|streetfood|Connection refused|RTMP|error' | tail -60 + +cd /opt/douyinWEB/backend +python3 - <<'PY' +import sqlite3, json, time +con=sqlite3.connect('data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +r=dict(con.execute('select * from yt_relay_states where group_id=?',(gid,)).fetchone() or {}) +print('=== STATE ===') +for k in ('status','error','ffmpeg_pid','push_seconds','started_at','updated_at','anchor_name'): + print(k, r.get(k)) +print('updated_age', round(time.time()-float(r.get('updated_at') or 0),1)) +log=r.get('recent_log') +try: + lines=json.loads(log) if isinstance(log,str) and log.startswith('[') else (log or '').splitlines() +except Exception: + lines=[str(log)] +print('=== FULL LOG (%d) ===' % len(lines)) +for ln in lines: + print(ln if isinstance(ln,str) else ln) +# any other groups pushing? +print('=== OTHER RELAY ===') +for row in con.execute("select group_id,status,ffmpeg_pid,substr(error,1,80) err from yt_relay_states where status not in ('idle','stopped','paused_exclusive') or ffmpeg_pid>0"): + print(dict(row)) +PY +""", + timeout=45, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_assign_category.py b/scripts/_deploy_assign_category.py new file mode 100644 index 0000000..e0a8bee --- /dev/null +++ b/scripts/_deploy_assign_category.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Deploy per-group assign category (普通/时间段) to physical + VPS.""" +import paramiko +import sys +from pathlib import Path + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/yt_assign_db.py", + "backend/app/models.py", + "backend/app/main.py", + "backend/app/youtube_relay_pipeline.py", + "frontend/src/components/YtAssignPanel.tsx", +] + + +def put(c, root, sudo=None): + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_cat_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((LOCAL / rel).read_bytes()) + dst = f"{root}/{rel}" + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc \"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + if sudo + else f"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + ) + c.exec_command(cmd, timeout=30)[1].read() + print("ok", rel, flush=True) + sftp.close() + + +def build_restart(c, sudo=None): + inner = ( + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_cat.log 2>&1 && echo FE_OK || (tail -20 /tmp/fe_cat.log; echo FE_FAIL); " + "systemctl restart douyinweb-api douyinweb-web; " + "systemctl is-active douyinweb-api; systemctl is-active douyinweb-web" + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc '{inner}'" if sudo else inner + _i, o, e = c.exec_command(cmd, timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("PHYS", flush=True) +put(p, "/opt/douyinWEB", "4669805") +build_restart(p, "4669805") +p.close() + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("VPS", flush=True) +put(v, "/opt/douyinWEB") +build_restart(v) +v.close() +print("DONE", flush=True) diff --git a/scripts/_deploy_assign_lives_sync.py b/scripts/_deploy_assign_lives_sync.py new file mode 100644 index 0000000..5aae921 --- /dev/null +++ b/scripts/_deploy_assign_lives_sync.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy assign_lives hub sync + receiving-first live-map; push catalog; verify.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = { + "/opt/douyinWEB/backend/app/youtube_live.py": (ROOT / "backend/app/youtube_live.py").read_bytes(), + "/opt/douyinWEB/backend/app/ops_neko.py": (ROOT / "backend/app/ops_neko.py").read_bytes(), + "/opt/douyinWEB/backend/app/main.py": (ROOT / "backend/app/main.py").read_bytes(), + "/opt/douyinWEB/youtube-svc/src/youtube.mjs": (ROOT / "youtube-svc/src/youtube.mjs").read_bytes(), +} + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return str(ex) + + +def deploy(port, user, pw, sudo=False): + print(f"\n===== {user}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, (dst, data) in enumerate(FILES.items()): + tmp = f"/tmp/_dep_{i}" + with sftp.file(tmp, "wb") as f: + f.write(data) + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat {tmp} > {dst}\"", 30) + else: + run(c, f"cat {tmp} > {dst}", 20) + sftp.close() + restart = "systemctl restart douyinweb-yt; systemctl restart douyinweb-api" + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' bash -lc {repr(restart)}", 50) + else: + run(c, restart + " >/tmp/r.log 2>&1 &", 15) + for i in range(16): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print("health", h) + if h.endswith("200"): + break + if i == 7: + kill = "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api" + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' bash -lc {repr(kill)}", 40) + else: + run(c, kill, 40) + c.close() + + +def push_and_verify(): + # physical: push catalog + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=25) + print("\n===== push catalog =====") + print( + run( + c, + "echo '4669805' | sudo -S -p '' bash -lc \"curl -sS -m 60 -X POST -H 'Cookie: ' " + "http://127.0.0.1:8014/api/ops/neko/push-catalog\"", + 90, + )[:1500] + ) + # login + push via python with session + script = r''' +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req,timeout=10).status) +req=urllib.request.Request("http://127.0.0.1:8014/api/ops/neko/push-catalog", data=b"{}", headers={"Content-Type":"application/json"}, method="POST") +raw=op.open(req, timeout=90).read() +print("push", raw[:800]) +req=urllib.request.Request("http://127.0.0.1:8014/api/youtube/live-map?force=1") +p=json.loads(op.open(req, timeout=150).read()) +print("phys live_count", p.get("live_count"), p.get("source")) +for k,v in sorted((p.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", (v.get("title") or k)[:28], v.get("source")) +''' + sftp = c.open_sftp() + with sftp.file("/tmp/_pushv.py", "w") as f: + f.write(script) + sftp.close() + print(run(c, "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_pushv.py", 220)[:2500]) + c.close() + + # vps verify + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25) + print("\n===== vps after sync =====") + print(run(c, "/opt/douyinWEB/backend/.venv/bin/python /tmp/_pushv.py", 220)[:2500]) + # write same script on vps + sftp = c.open_sftp() + with sftp.file("/tmp/_pushv.py", "w") as f: + f.write(script.replace("push-catalog", "ops/neko/sync-status").replace( + 'req=urllib.request.Request("http://127.0.0.1:8014/api/ops/neko/push-catalog", data=b"{}", headers={"Content-Type":"application/json"}, method="POST")\nraw=op.open(req, timeout=90).read()\nprint("push", raw[:800])\n', + 'print("skip push on hub")\n' + )) + sftp.close() + # simpler vps-only verify + vscript = r''' +import json,urllib.request,http.cookiejar,sqlite3 +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req,timeout=10).status) +con=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +rows=list(con.execute("select ts,youtube_channel_id,on_air,live_status,detect_source,neko_ref from yt_studio_samples where on_air=1 order by ts desc limit 10")) +print("hub on_air samples", len(rows)) +for r in rows: + print(" ", r) +p=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=150).read()) +print("vps live_count", p.get("live_count"), p.get("source")) +for k,v in sorted((p.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", (v.get("title") or k)[:28], v.get("source"), (v.get("live_url") or "")[:55]) +''' + with sftp.file("/tmp/_vpsv.py", "w") as f: + f.write(vscript) + sftp.close() + print(run(c, "/opt/douyinWEB/backend/.venv/bin/python /tmp/_vpsv.py", 220)[:3000]) + c.close() + + +if __name__ == "__main__": + deploy(22, "root", "Xiao4669805", sudo=False) + deploy(4014, "eric", "4669805", sudo=True) + push_and_verify() diff --git a/scripts/_deploy_assign_oauth_live.py b/scripts/_deploy_assign_oauth_live.py new file mode 100644 index 0000000..c173c26 --- /dev/null +++ b/scripts/_deploy_assign_oauth_live.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy youtubei+OAuth assign live-map; verify both hosts match.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend" / "app" / "youtube_live.py" + +VERIFY = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live, yt_assign_db, db + +async def main(): + youtube_live._LAST_OAUTH_AT = 0.0 # force OAuth this tick + gs = [g for g in yt_assign_db.list_groups(include_urls=False) if g.get("enabled")] + with_pk = 0 + with_tok = 0 + for g in gs: + pk = str(g.get("channel_pk") or "").strip() + cid = str(g.get("youtube_channel_id") or "").strip() + tok = False + if pk: + with_pk += 1 + ch = db.get_shorts_channel(pk) or {} + tok = bool(str(ch.get("refresh_token") or "").strip()) + if tok: + with_tok += 1 + print(f" card {g.get('name')} cid={cid} pk={pk[:8] if pk else '-'} oauth_token={tok}") + print("cards", len(gs), "with_pk", with_pk, "with_oauth_token", with_tok) + m = await youtube_live.build_live_map(force=True) + entries = m.get("entries") or {} + live = [(k, v.get("source"), (v.get("title") or "")[:36]) for k, v in entries.items() if v.get("is_live")] + assign_live = [x for x in live if x[0].startswith("assign:")] + print("live_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:80]) + print("assign_live", len(assign_live), "all_live_entries", len(live)) + for row in assign_live: + print(" LIVE", row) + # sample offline public answers + n_yt = n_oa = 0 + for k, v in entries.items(): + if not k.startswith("assign:"): + continue + s = str(v.get("source") or "") + if s == "youtubei": + n_yt += 1 + if s.startswith("oauth"): + n_oa += 1 + print("assign_entries_youtubei_src", n_yt, "oauth_src", n_oa) + +asyncio.run(main()) +''' + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def deploy(host, port, user, pw, sudo=False): + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_yt_live_oa.py", "wb") as f: + f.write(LOCAL.read_bytes()) + with sftp.file("/tmp/_verify_oa_live.py", "w") as f: + f.write(VERIFY) + sftp.close() + dst = "/opt/douyinWEB/backend/app/youtube_live.py" + if sudo: + print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat /tmp/_yt_live_oa.py > {dst}\"", 30).strip()) + run(c, f"echo '{pw}' | sudo -S -p '' systemctl restart douyinweb-api", 45) + else: + print(run(c, f"cat /tmp/_yt_live_oa.py > {dst} && echo OK", 20).strip()) + run(c, "systemctl restart douyinweb-api >/tmp/_rst.log 2>&1 &", 10) + for i in range(12): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x", 10).strip() + a = run(c, "systemctl is-active douyinweb-api", 8).strip() + print(f" try{i} {a} {h}") + if h == "200": + break + if "deactivat" in a and i == 5: + run( + c, + "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", + 30, + ) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_oa_live.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 180)[:3500]) + c.close() + + +def main(): + deploy("107.173.30.245", 22, "root", "Xiao4669805", False) + deploy("107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_assign_youtubei_live.py b/scripts/_deploy_assign_youtubei_live.py new file mode 100644 index 0000000..f4ae4e1 --- /dev/null +++ b/scripts/_deploy_assign_youtubei_live.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy assign→youtubei live-map fix; verify both hosts.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend" / "app" / "youtube_live.py" + + +def run(c, cmd, t=90): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def deploy_one(host, port, user, pw, sudo=False): + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + tmp = "/tmp/_youtube_live_assign_yt.py" + with sftp.file(tmp, "wb") as f: + f.write(LOCAL.read_bytes()) + sftp.close() + dst = "/opt/douyinWEB/backend/app/youtube_live.py" + if sudo: + print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat {tmp} > {dst}\"", 30).strip()) + else: + print(run(c, f"cat {tmp} > {dst} && echo OK", 20).strip()) + print("marker", run(c, f"grep -c 'Assign cards: same public youtubei' {dst}", 10).strip()) + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' systemctl restart douyinweb-api", 40) + else: + run(c, "systemctl restart douyinweb-api >/tmp/_rst.log 2>&1 &", 10) + for i in range(12): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x", 10).strip() + a = run(c, "systemctl is-active douyinweb-api", 8).strip() + print(f" try{i} {a} {h}") + if h == "200": + break + if a == "deactivating" and i == 5: + run(c, "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", 30) + # verify live-map + verify = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0,".") +from app import youtube_live, yt_assign_db +async def main(): + gs=[g for g in yt_assign_db.list_groups(include_urls=False) if g.get("enabled") and (g.get("youtube_channel_id") or g.get("channel_pk"))] + print("assign_cards", len(gs)) + for g in gs[:12]: + print(" ", g.get("name"), g.get("youtube_channel_id")) + m=await youtube_live.build_live_map(force=True) + live=[(k,v.get("source"),(v.get("title") or "")[:36]) for k,v in (m.get("entries") or {}).items() if v.get("is_live") and str(k).startswith("assign:")] + print("live_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:80]) + print("assign_live", len(live)) + for row in live: + print(" ", row) +asyncio.run(main()) +''' + sftp = c.open_sftp() + with sftp.file("/tmp/_verify_assign_yt.py", "w") as f: + f.write(verify) + sftp.close() + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_assign_yt.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 150)[:2500]) + c.close() + + +def main(): + deploy_one("107.173.30.245", 22, "root", "Xiao4669805", False) + deploy_one("107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_audit_bugfixes_dual.py b/scripts/_deploy_audit_bugfixes_dual.py new file mode 100644 index 0000000..9be20d0 --- /dev/null +++ b/scripts/_deploy_audit_bugfixes_dual.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Deploy audit bugfixes dual + revive hung dy API. Never recreate Neko.""" +from __future__ import annotations + +import io +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +DY = "108.174.50.68" +DYLIVE = "107.173.30.245" +TGZ = "/tmp/dy_next_audit_fix.tgz" + +FILES = [ + "backend/app/youtube_relay_pipeline.py", + "backend/app/youtube_relay_status.py", + "backend/app/main.py", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/lib/ytRelayStatus.ts", + "backend/tests/test_relay_paused_status.py", +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, cmd: str, t: int = 1200) -> tuple[int, str]: + print(f"\n===== {cmd[:100].replace(chr(10), ' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return code, out + + +def put_text(sftp, local: Path, remote: str) -> None: + raw = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(raw) + + +for rel in FILES: + assert (ROOT / rel).is_file(), rel + +# ---------- dy ---------- +print("=== DY ===", flush=True) +dy = connect(DY) +run( + dy, + "ps -o pid,stat,etime,cmd -p $(pgrep -f 'uvicorn app.main' | head -1) 2>/dev/null; " + "systemctl is-active douyinweb-api; free -h | head -2", +) +sftp = dy.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +sftp.close() + +code, _ = run( + dy, + rf""" +set -euo pipefail +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/youtube_relay_status.py /opt/douyinWEB/backend/app/youtube_relay_status.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/ytRelayStatus.ts /opt/douyinWEB/frontend/src/lib/ytRelayStatus.ts +install -m 0644 /tmp/test_relay_paused_status.py /opt/douyinWEB/backend/tests/test_relay_paused_status.py + +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app.youtube_relay_status import summarize_relay_group as s; r=s(group={{"id":"g","enabled":True,"has_stream_key":True,"stream_key":"k","featured":[{{"url":"https://live.douyin.com/1"}}]}}, st={{"status":"paused_exclusive","error":"独占","recent_log":[]}}, session_running=False, pipeline_enabled=True, lane_armed=True); assert r["business_status"]=="paused_exclusive"; print("status_ok")' +grep -n 'time_slot_mode on but no time_slot' app/youtube_relay_pipeline.py | head -1 +grep -n '24/N 窗口限制' app/youtube_relay_pipeline.py | head -1 + +# revive hung API (D-state) +systemctl restart douyinweb-api +sleep 5 +systemctl is-active douyinweb-api +curl -sS -m 15 -o /dev/null -w 'health:%{{http_code}}\n' http://127.0.0.1:8014/api/health + +cd /opt/douyinWEB/frontend +NODE_OPTIONS='--max-old-space-size=1536' npm run build +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +rm -f {TGZ} +tar -C /opt/douyinWEB/frontend -czf {TGZ} .next +ls -lh {TGZ} +curl -sS -m 15 -o /dev/null -w 'youtube:%{{http_code}}\n' http://127.0.0.1:4015/youtube +docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort +echo DY_DONE +""", + t=1800, +) +if code != 0: + dy.close() + raise SystemExit(f"dy failed {code}") + +sftp = dy.open_sftp() +buf = io.BytesIO() +sftp.getfo(TGZ, buf) +sftp.close() +dy.close() +print(f"tarball={buf.tell()}", flush=True) + +# ---------- dylive ---------- +print("=== DYLIVE ===", flush=True) +dl = connect(DYLIVE) +sftp = dl.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +buf.seek(0) +with sftp.file(TGZ, "wb") as f: + f.write(buf.getvalue()) +sftp.close() + +code, _ = run( + dl, + rf""" +set -euo pipefail +BEFORE=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo BEFORE=$BEFORE +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/youtube_relay_status.py /opt/douyinWEB/backend/app/youtube_relay_status.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/ytRelayStatus.ts /opt/douyinWEB/frontend/src/lib/ytRelayStatus.ts +install -m 0644 /tmp/test_relay_paused_status.py /opt/douyinWEB/backend/tests/test_relay_paused_status.py +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app.youtube_relay_status import summarize_relay_group as s; r=s(group={{"id":"g","enabled":True,"has_stream_key":True,"stream_key":"k","featured":[{{"url":"https://live.douyin.com/1"}}]}}, st={{"status":"paused_exclusive","error":"独占","recent_log":[]}}, session_running=False, pipeline_enabled=True, lane_armed=True); assert r["business_status"]=="paused_exclusive"; print("status_ok")' +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api +curl -sS -m 12 -o /dev/null -w 'health:%{{http_code}}\n' http://127.0.0.1:8014/api/health +cd /opt/douyinWEB/frontend +rm -rf .next.bak-audit +[ -d .next ] && mv .next .next.bak-audit || true +tar -xzf {TGZ} +test -d .next +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +curl -sS -m 12 -o /dev/null -w 'youtube:%{{http_code}}\n' http://127.0.0.1:4015/youtube +AFTER=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo AFTER=$AFTER +docker exec douyinweb-neko-6 supervisorctl status google-chrome 2>/dev/null || true +free -m | head -2 +echo DYLIVE_DONE +""", + t=300, +) +dl.close() +if code != 0: + raise SystemExit(f"dylive failed {code}") +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_batch2_ux_quota_neko.py b/scripts/_deploy_batch2_ux_quota_neko.py new file mode 100644 index 0000000..adec985 --- /dev/null +++ b/scripts/_deploy_batch2_ux_quota_neko.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy batch2: busy split, quota UI, neko CDP watch, live align, yt-long gap.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] +FILES = [ + ("frontend/src/components/YtAssignPanel.tsx", "/opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx"), + ("frontend/src/app/shorts/page.tsx", "/opt/douyinWEB/frontend/src/app/shorts/page.tsx"), + ("backend/app/shorts_yt_quota.py", "/opt/douyinWEB/backend/app/shorts_yt_quota.py"), + ("backend/app/shorts_pipeline.py", "/opt/douyinWEB/backend/app/shorts_pipeline.py"), + ("backend/app/yt_long_db.py", "/opt/douyinWEB/backend/app/yt_long_db.py"), + ("scripts/linux/neko_health_watch.sh", "/opt/douyinWEB/scripts/linux/neko_health_watch.sh"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +# Install watch script to common locations if present (no edge service touch). +for dst in /opt/douyinWEB/scripts/linux/neko_health_watch.sh /usr/local/bin/neko_health_watch.sh; do + if [ -f "$dst" ] || [ -d "$(dirname "$dst")" ]; then + install -m 755 /tmp/_neko_health_watch.sh "$dst" 2>/dev/null || cp -a /tmp/_neko_health_watch.sh "$dst" + echo "watch_installed $dst" + fi +done +# Restart only douyinweb-neko-watch if unit exists — never sing-box/frpp/wg. +if systemctl list-unit-files 2>/dev/null | grep -q '^douyinweb-neko-watch'; then + systemctl restart douyinweb-neko-watch.service || true + systemctl is-active douyinweb-neko-watch.service || true +fi +cd /opt/douyinWEB/backend +.venv/bin/python - <<'PY' +from app.shorts_yt_quota import quota_budgets_by_profile +from app import db +rows=quota_budgets_by_profile(db.get_settings_map()) +for r in rows: + assert not (r.get("blocked") and r.get("exhausted_hint")), r +print("quota_split_ok", [(r["id"], r["exhausted_hint"], r["blocked"]) for r in rows]) +PY +systemctl restart douyinweb-api +for i in $(seq 1 18); do + c=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health_$i=$c + [ "$c" = "200" ] && break + sleep 2 +done +cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -20 +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + for rel, dst in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + tmp = f"/tmp/_b2_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + if rel.endswith("neko_health_watch.sh"): + with sftp.file("/tmp/_neko_health_watch.sh", "wb") as f: + f.write(data) + _, o, e = c.exec_command( + f"mkdir -p $(dirname {dst}); cat {tmp} > {dst} && echo OK {dst}", + timeout=30, + ) + print((o.read() + e.read()).decode()[:180], flush=True) + with sftp.file("/tmp/_deploy_batch2.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_batch2.sh", timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace")[-5000:], flush=True) + c.close() + + +def main(): + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_cdp_end_confirm.py b/scripts/_deploy_cdp_end_confirm.py new file mode 100644 index 0000000..1502285 --- /dev/null +++ b/scripts/_deploy_cdp_end_confirm.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/neko/cdp_end_stream.py"), "/tmp/cdp_end_stream.py") +sftp.close() +_, o, e = c.exec_command( + "install -m 0644 /tmp/cdp_end_stream.py /opt/douyinWEB/backend/neko/cdp_end_stream.py && " + "grep -n 'Not yet\\|CONFIRM_EXACT\\|pre_confirm' /opt/douyinWEB/backend/neko/cdp_end_stream.py | head -20 && " + "echo DONE", + timeout=30, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_deploy_channel_analytics.py b/scripts/_deploy_channel_analytics.py new file mode 100644 index 0000000..a6ecf7e --- /dev/null +++ b/scripts/_deploy_channel_analytics.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +"""Deploy channel analytics page + API to phys+VPS.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/yt_studio_db.py", + "backend/app/main.py", + "frontend/src/app/youtube/analytics/[groupId]/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_an_${i}.path" ]; do + rel=$(cat "/tmp/_dy_an_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_an_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service + +cd "$ROOT/frontend" +npm run build >/tmp/dy_an_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -50 /tmp/dy_an_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service + +grep -nE 'build_group_analytics|/analytics|数据' \ + "$ROOT/backend/app/yt_studio_db.py" "$ROOT/backend/app/main.py" \ + "$ROOT/frontend/src/components/YtAssignPanel.tsx" | head -20 + +# smoke: pick first assign group +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, urllib.request +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +# cookie via opener +import http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +op.open(req, timeout=20) +gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=30).read().decode()) +groups=gs.get('groups') or gs if isinstance(gs, list) else (gs.get('groups') or []) +print('groups', len(groups)) +if groups: + gid=str(groups[0].get('id') or '') + an=json.loads(op.open(f'http://127.0.0.1:8014/api/youtube/assign/groups/{gid}/analytics?days=14', timeout=60).read().decode()) + print('analytics_ok', an.get('ok'), 'sessions', (an.get('overview') or {}).get('session_count'), 'samples', (an.get('window') or {}).get('sample_count'), 'name', (an.get('group') or {}).get('name')) +PY +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_an_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_an_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_an_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_an_remote.sh" if sudo else "bash /tmp/_dy_an_remote.sh" + _, o, e = c.exec_command(cmd, timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("done") diff --git a/scripts/_deploy_continue_live.py b/scripts/_deploy_continue_live.py index c8497f9..868a9ed 100644 --- a/scripts/_deploy_continue_live.py +++ b/scripts/_deploy_continue_live.py @@ -1,146 +1,122 @@ +#!/usr/bin/env python3 # -*- coding: utf-8 -*- -"""Deploy scrape fix + extension ingest order; optional soft Chrome restart for SW reload.""" +"""Deploy remaining live-map / studio / ops-neko / youtube-svc / FE to both hosts.""" from __future__ import annotations -import time +import sys from pathlib import Path import paramiko -PASS = "4669805" -ROOT = Path(__file__).resolve().parents[1] -SOFT_CHROME = False # NEVER restart Chrome on deploy — signs Google out - +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] FILES = [ - ("backend/app/youtube_neko.py", "/opt/douyinWEB/backend/app/youtube_neko.py", "_c3_neko.py"), - ("backend/neko/cdp_studio_scrape.py", "/opt/douyinWEB/backend/neko/cdp_studio_scrape.py", "_c3_scrape.py"), - ( - "backend/neko/live-ops-extension/background.js", - "/opt/douyinWEB/backend/neko/live-ops-extension/background.js", - "_c3_bg.js", - ), - ( - "backend/neko/live-ops-extension/content.js", - "/opt/douyinWEB/backend/neko/live-ops-extension/content.js", - "_c3_ct.js", - ), - ("scripts/_probe_telemetry_detail.py", "/tmp/_probe_telemetry_detail.py", "_probe_telemetry_detail.py"), + "backend/app/db.py", + "backend/app/host_profile.py", + "backend/app/models.py", + "backend/app/ops_neko.py", + "backend/app/ops_neko_db.py", + "backend/app/ops_neko_sync.py", + "backend/app/session_auth.py", + "backend/app/youtube_live.py", + "backend/app/youtube_neko.py", + "backend/app/yt_studio_db.py", + "backend/neko/cdp_studio_scrape.py", + "backend/neko/live-ops-extension/background.js", + "backend/neko/live-ops-extension/content.js", + "youtube-svc/src/youtube.mjs", + "frontend/src/app/neko/page.tsx", + "frontend/src/components/OpsNekoHubCredentialsCard.tsx", + "frontend/src/components/YtRelayOpsHero.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/lib/ytRelayStatus.ts", ] -SH = r"""#!/bin/bash -set -euo pipefail -install -m 644 /tmp/_c3_neko.py /opt/douyinWEB/backend/app/youtube_neko.py -install -m 644 /tmp/_c3_scrape.py /opt/douyinWEB/backend/neko/cdp_studio_scrape.py -install -m 644 /tmp/_c3_bg.js /opt/douyinWEB/backend/neko/live-ops-extension/background.js -install -m 644 /tmp/_c3_ct.js /opt/douyinWEB/backend/neko/live-ops-extension/content.js -cd /opt/douyinWEB/backend && .venv/bin/python -m py_compile app/youtube_neko.py -BEFORE=$(docker ps -q --filter name=douyinweb-neko- | wc -l | tr -d ' ') -systemctl restart douyinweb-api -sleep 4 -systemctl is-active douyinweb-api -AFTER=$(docker ps -q --filter name=douyinweb-neko- | wc -l | tr -d ' ') -echo "NEKO_BEFORE=$BEFORE NEKO_AFTER=$AFTER" -# Smoke scrape via stdin (no docker cp) -echo SMOKE_SCRAPE -python3 - <<'PY' -import subprocess -from pathlib import Path -script = Path('/opt/douyinWEB/backend/neko/cdp_studio_scrape.py').read_text(encoding='utf-8') -for idx in (1, 5, 6): - name = f'douyinweb-neko-{idx}' - p = subprocess.run(['docker','exec','-i',name,'python3','-'], input=script, capture_output=True, text=True, timeout=30) - line = (p.stdout or p.stderr or '').strip().splitlines()[-1] if (p.stdout or p.stderr) else '' - print(name, 'rc', p.returncode, line[:220]) -PY - -SOFT_CHROME=__SOFT__ -if [ "$SOFT_CHROME" = "1" ]; then - echo "=== soft restart google-chrome (profile kept) ===" - for name in $(docker ps --filter name=douyinweb-neko- --format '{{.Names}}' | sort -V); do - echo -n "$name " - docker exec "$name" supervisorctl restart google-chrome 2>/dev/null \ - || docker exec "$name" supervisorctl restart chromium 2>/dev/null \ - || echo "no_supervisor_chrome" - done - sleep 20 - # Re-open Studio URLs if session restore missed livestreaming - python3 - <<'PY' -import json, subprocess, urllib.parse -URLS = { - 1: "https://studio.youtube.com/video/9tMkUp0iUH8/livestreaming", - 2: "https://studio.youtube.com/video/zHthtNjrbeo/livestreaming", - 3: "https://studio.youtube.com/video/8NeMVAjx0r4/livestreaming", - 4: "https://studio.youtube.com/video/-kkCblUC8XM/livestreaming", - 5: "https://studio.youtube.com/video/31s_VgR215k/livestreaming", - 6: "https://studio.youtube.com/video/IKGJwKAZGWM/livestreaming", - 7: "https://studio.youtube.com/video/i6szUMA25RM/livestreaming", -} -def run(cmd, timeout=25): - p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) - return p.returncode, (p.stdout or "") + (p.stderr or "") -for idx, url in URLS.items(): - name = f"douyinweb-neko-{idx}" - # if already has livestreaming tab, skip - py_check = "import json,urllib.request; tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read().decode()); print(sum(1 for t in tabs if 'livestreaming' in (t.get('url') or '')))" - code, out = run(["docker", "exec", name, "python3", "-c", py_check]) - if (out or "").strip().splitlines()[-1:] == ["1"] or (out or "").strip().endswith("1"): - print(name, "already_live_tab") - continue - py = f''' -import json, urllib.request -url = {url!r} -req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + url, method="PUT") -with urllib.request.urlopen(req, timeout=10) as r: - print(r.read()[:80]) -''' - code, out = run(["docker", "exec", name, "python3", "-c", py]) - print(name, "reopen", (out or "")[:80].replace("\\n"," ")) -PY - sleep 15 -fi - -echo PROBE -/opt/douyinWEB/backend/.venv/bin/python /tmp/_probe_telemetry_detail.py -docker ps --filter name=douyinweb-neko- --format '{{.Names}} {{.Status}}' -echo DONE -""".replace("__SOFT__", "1" if SOFT_CHROME else "0") - - -def main() -> int: - c = paramiko.SSHClient() - c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - for i in range(10): - try: - c.connect( - "107.173.30.245", - 4014, - "eric", - PASS, - timeout=60, - banner_timeout=120, - allow_agent=False, - look_for_keys=False, - ) - break - except Exception as ex: - print("ssh", i, type(ex).__name__) - time.sleep(2) - else: - return 1 +def put(c: paramiko.SSHClient, root: str, sudo: str | None = None) -> None: sftp = c.open_sftp() - for rel, _dst, tmp in FILES: - with sftp.file(f"/tmp/{tmp}", "wb") as f: - f.write((ROOT / rel).read_bytes()) - print("up", rel) - with sftp.file("/tmp/_c3_deploy.sh", "w") as f: - f.write(SH) + for rel in FILES: + tmp = f"/tmp/_cont_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((LOCAL / rel).read_bytes()) + dst = f"{root}/{rel}".replace("\\", "/") + parent = str(Path(dst).parent).replace("\\", "/") + if sudo: + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc " + f"\"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + ) + else: + cmd = f"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + c.exec_command(cmd, timeout=40)[1].read() + print("ok", rel, flush=True) sftp.close() - _, o, e = c.exec_command(f"echo '{PASS}' | sudo -S -p '' bash /tmp/_c3_deploy.sh", timeout=600) - print((o.read() + e.read()).decode("utf-8", "replace")) - c.close() - return 0 + + +def build_restart(c: paramiko.SSHClient, sudo: str | None = None) -> None: + inner = ( + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_cont.log 2>&1 " + "&& echo FE_OK || (tail -30 /tmp/fe_cont.log; echo FE_FAIL); " + "systemctl restart douyinweb-yt douyinweb-api douyinweb-web; " + "sleep 3; " + "systemctl is-active douyinweb-yt; systemctl is-active douyinweb-api; systemctl is-active douyinweb-web; " + "for i in 1 2 3 4 5 6 7 8; do " + " code=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x); " + " echo health=$code; " + " [ \"$code\" = 200 ] && break; sleep 2; " + "done" + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc {repr(inner)}" if sudo else inner + _, o, e = c.exec_command(cmd, timeout=900) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def verify(c: paramiko.SSHClient, sudo: str | None = None) -> None: + script = r''' +import json, urllib.request, http.cookiejar, time +for i in range(10): + try: + print("health", urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=3).status) + break + except Exception as e: + print("wait", i, type(e).__name__); time.sleep(2) +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req, timeout=15).status) +p=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=150).read()) +print("live_count", p.get("live_count"), "source", p.get("source")) +ex=json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=20).read()) +print("exclude", ex.get("ok"), "count", ex.get("count"), "effective", ex.get("effective_room_count")) +''' + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_cont_v.py", "w") as f: + f.write(script) + sftp.close() + cmd = f"echo '{sudo}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_cont_v.py" + _, o, e = c.exec_command(cmd, timeout=200) + else: + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -", timeout=200) + o.channel.sendall(script.encode()) + o.channel.shutdown_write() + print((o.read() + e.read()).decode("utf-8", "replace")[:2500], flush=True) + + +def main() -> None: + for port, user, pwd, label, sudo in [ + (4014, "eric", "4669805", "PHYS", "4669805"), + (22, "root", "Xiao4669805", "VPS", None), + ]: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pwd, timeout=40, allow_agent=False, look_for_keys=False) + print(f"===== {label} =====", flush=True) + put(c, "/opt/douyinWEB", sudo) + build_restart(c, sudo) + verify(c, sudo) + c.close() + print("DONE", flush=True) if __name__ == "__main__": - raise SystemExit(main()) + main() diff --git a/scripts/_deploy_covers_keep_2d_both.py b/scripts/_deploy_covers_keep_2d_both.py new file mode 100644 index 0000000..0c7fb1d --- /dev/null +++ b/scripts/_deploy_covers_keep_2d_both.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Ship cover retention to dy as well; verify both.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +FILES = [ + "backend/app/s3_storage.py", + "backend/app/clip_retention.py", + "backend/app/db.py", +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + return c + except Exception as e: + print(host, e, flush=True) + time.sleep(1 + i) + raise SystemExit(f"fail {host}") + + +def put_all(c): + sftp = c.open_sftp() + for rel in FILES: + data = (ROOT / rel.replace("/", "\\")).read_bytes() + h = hashlib.sha256(data).hexdigest()[:12] + remote = f"/opt/douyinWEB/{rel}" + with sftp.file(remote, "wb") as f: + f.write(data) + print(f" {h} {rel}", flush=True) + sftp.close() + + +def apply(host, name): + print(f"\n=== {name} {host} ===", flush=True) + c = connect(host) + put_all(c) + cmd = r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +db.update_settings_map({"covers_s3_keep_days": 2}) +print("covers_s3_keep_days=", db.get_settings_map().get("covers_s3_keep_days")) +from app.clip_retention import disk_ok_for_record, disk_free_gb +print("free_gb=", round(disk_free_gb(),2), "disk_ok=", disk_ok_for_record()) +PY +systemctl restart douyinweb-api +sleep 2 +echo api=$(systemctl is-active douyinweb-api) +df -h / | awk 'NR==2{print}' +""" + _i, o, e = c.exec_command(cmd, timeout=90) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:500], flush=True) + c.close() + + +apply("107.173.30.245", "dylive") +apply("108.174.50.68", "dy") +print("BOTH_DONE", flush=True) diff --git a/scripts/_deploy_covers_keep_2d_dylive.py b/scripts/_deploy_covers_keep_2d_dylive.py new file mode 100644 index 0000000..948fcbb --- /dev/null +++ b/scripts/_deploy_covers_keep_2d_dylive.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Deploy cover 2-day retention + run purge on dylive; verify disk_ok.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +HOST = "107.173.30.245" +FILES = [ + "backend/app/s3_storage.py", + "backend/app/clip_retention.py", + "backend/app/db.py", +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh {host} try {i}", flush=True) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + print("ok", flush=True) + return c + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + raise SystemExit(f"ssh_fail {host}") + + +def put(c, rel): + local = ROOT / rel.replace("/", "\\") + remote = f"/opt/douyinWEB/{rel}" + h = hashlib.sha256(local.read_bytes()).hexdigest()[:12] + print(f"put {rel} {h}", flush=True) + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + sftp.close() + return h + + +def run(c, cmd, timeout=300): + print(f"$ {cmd[:100]}...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + start = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.recv_stderr_ready(): + sys.stdout.write(chan.recv_stderr(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.12) + code = chan.recv_exit_status() + print(f"\n[exit {code}]", flush=True) + return code + + +def main(): + c = connect(HOST) + for rel in FILES: + put(c, rel) + code = run( + c, + r""" +set -e +cd /opt/douyinWEB/backend +# persist setting +./.venv/bin/python - <<'PY' +from app import db +db.update_settings_map({"covers_s3_keep_days": 2}) +print("covers_s3_keep_days", db.get_settings_map().get("covers_s3_keep_days")) +PY +systemctl restart douyinweb-api +sleep 2 +echo api=$(systemctl is-active douyinweb-api) +# one-shot purge (may take a while if many objects) +./.venv/bin/python - <<'PY' +import json +from app import s3_storage, db +from app.clip_retention import disk_ok_for_record, disk_free_gb +cfg=db.get_settings_map() +print("free_gb", round(disk_free_gb(),2), "disk_ok", disk_ok_for_record(cfg)) +r=s3_storage.purge_covers_older_than(keep_days=float(cfg.get("covers_s3_keep_days") or 2), max_delete=20000) +print(json.dumps(r, ensure_ascii=False)) +print("free_after", round(disk_free_gb(),2)) +PY +# try seaweed vacuum if weed binary present +which weed || true +weed version 2>/dev/null || true +# volume vacuum via master HTTP if available +curl -sS -m 10 'http://127.0.0.1:19333/vol/vacuum?garbageThreshold=0.01' || true +echo +df -h / +du -sh /data/seaweed 2>/dev/null +""", + timeout=400, + ) + c.close() + if code != 0: + raise SystemExit(code) + print("COVER_POLICY_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_dropdown_fix.py b/scripts/_deploy_dropdown_fix.py new file mode 100644 index 0000000..fbb06bd --- /dev/null +++ b/scripts/_deploy_dropdown_fix.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import paramiko +import sys +from pathlib import Path + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayOpsHero.tsx", +] + +def put(c, root, sudo=None): + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_dd_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((LOCAL / rel).read_bytes()) + dst = f"{root}/{rel}" + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc \"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + if sudo + else f"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + ) + c.exec_command(cmd, timeout=30)[1].read() + print("ok", rel, flush=True) + sftp.close() + +def build(c, sudo=None): + inner = ( + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_dd.log 2>&1 && echo FE_OK || (tail -15 /tmp/fe_dd.log; echo FE_FAIL); " + "systemctl restart douyinweb-web; systemctl is-active douyinweb-web" + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc '{inner}'" if sudo else inner + _i, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + +p = paramiko.SSHClient(); p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("PHYS", flush=True); put(p, "/opt/douyinWEB", "4669805"); build(p, "4669805"); p.close() +v = paramiko.SSHClient(); v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("VPS", flush=True); put(v, "/opt/douyinWEB"); build(v); v.close() +print("DONE", flush=True) diff --git a/scripts/_deploy_dy_cdp_running_fix.py b/scripts/_deploy_dy_cdp_running_fix.py new file mode 100644 index 0000000..3e2b4e6 --- /dev/null +++ b/scripts/_deploy_dy_cdp_running_fix.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Deploy youtube_neko CDP fix to dy and force-scrape neko 6 — live prints.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +HOST = "108.174.50.68" +REL = "backend/app/youtube_neko.py" + + +def main(): + data = (ROOT / REL.replace("/", "\\")).read_bytes() + h = hashlib.sha256(data).hexdigest()[:12] + print(f"local {h}", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh try {i}", flush=True) + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + sftp = c.open_sftp() + with sftp.file(f"/opt/douyinWEB/{REL}", "wb") as f: + f.write(data) + sftp.close() + print("uploaded", flush=True) + cmd = r""" +set -e +cd /opt/douyinWEB/backend +grep -n 'relay may leave Chrome\|_neko_ids_for_cdp_poll\|allow_cdp=True' app/youtube_neko.py | head -15 +systemctl restart douyinweb-api +sleep 3 +echo api=$(systemctl is-active douyinweb-api) +./.venv/bin/python - <<'PY' +import json +from app import youtube_neko, yt_assign_db +print('poll_ids', youtube_neko._neko_ids_for_cdp_poll()) +r = youtube_neko.poll_studio_cdp_once() +print('poll', json.dumps(r, ensure_ascii=False)[:2000]) +# find nomadvlog +for g in yt_assign_db.list_groups(include_urls=False): + if int(g.get('neko_instance_id') or 0) == 6 and 'nomad' in str(g.get('name') or '').lower(): + snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=180) + print('GROUP', g.get('name'), 'enabled', g.get('neko_enabled')) + print('SNAP', json.dumps({k:snap.get(k) for k in [ + 'live_page_open','on_air','live_status','viewer_count','total_views','url','age_sec','detect_source','ui_source']}, ensure_ascii=False)) +PY +""" + _i, o, e = c.exec_command(cmd, timeout=180, get_pty=True) + chan = o.channel + t0 = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - t0 > 170: + print("TIMEOUT", flush=True) + break + time.sleep(0.15) + print("\n[exit", chan.recv_exit_status(), "]", flush=True) + c.close() + print("DY_FIXED", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_dy_sigill_oom.py b/scripts/_deploy_dy_sigill_oom.py new file mode 100644 index 0000000..9543526 --- /dev/null +++ b/scripts/_deploy_dy_sigill_oom.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""Sync SIGILL chrome flags + API memory hard-cap to dy.nomadro.live; recover neko/7.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" + + +def connect(retries: int = 10): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + auth_timeout=60, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {last}") + + +def run(c, cmd: str, t: int = 300) -> str: + print("\n=====", cmd[:100].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return out + + +text = LOCAL.read_text(encoding="utf-8") +for needle in ("no-wasm-simd", "PassageEmbeddings", "no-turbofan", "WebAssemblySimd"): + assert needle in text, f"missing {needle}" + +c = connect() + +# --- 0) inventory --- +run( + c, + r""" +set +e +echo '=== host ===' +hostname; free -h | head -3 +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +systemctl is-active douyinweb-api douyinweb-web 2>/dev/null +systemctl show douyinweb-api -p MemoryCurrent,MemoryHigh,MemoryMax,OOMScoreAdjust 2>/dev/null +""", +) + +# --- 1) API memory hard-cap (same as dylive) --- +run( + c, + r""" +set -euo pipefail +mkdir -p /etc/systemd/system/douyinweb-api.service.d +cat > /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf <<'EOF' +[Service] +MemoryAccounting=yes +MemoryHigh=700M +MemoryMax=900M +MemorySwapMax=256M +OOMPolicy=kill +OOMScoreAdjust=400 +EOF +systemctl daemon-reload +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +systemctl show douyinweb-api -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,OOMScoreAdjust,OOMPolicy +curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 220; echo +""", +) + +# --- 2) upload browser-launch, overwrite mounted inode --- +sftp = c.open_sftp() +tmp = "/tmp/browser-launch-dy-sigill.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) +sftp.close() + +run( + c, + rf""" +set -euo pipefail +mkdir -p /opt/douyinWEB/backend/neko +# ensure capacity so neko-7 exists +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env 2>/dev/null || true; set +a +./.venv/bin/python - <<'PY' || true +from app import youtube_neko as yn +print(yn.ensure_capacity(8, start_instances=set(), reconcile_running=False)) +PY + +# start neko-7 if not running +docker start douyinweb-neko-7 2>/dev/null || true +sleep 3 +docker ps -a --filter name=douyinweb-neko-7 --format '{{.Names}} {{.Status}}' + +# find mounted inode and overwrite in-place (Docker file bind keeps old inode after rename) +CTR_INO=$(docker exec douyinweb-neko-7 sh -c "ls -li /etc/neko/browser-launch.sh" 2>/dev/null | awk '{{print $1}}' || true) +echo CTR_INO=$CTR_INO +HOST_MATCH="" +if [ -n "$CTR_INO" ]; then + HOST_MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$CTR_INO" '$1==i {{print $NF; exit}}' || true) +fi +echo HOST_MATCH=$HOST_MATCH +if [ -n "$HOST_MATCH" ]; then + cat {tmp} > "$HOST_MATCH" +fi +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh + +# if still not visible, force-recreate neko-7 to remount +if ! docker exec douyinweb-neko-7 grep -q no-turbofan /etc/neko/browser-launch.sh 2>/dev/null; then + echo RECREATE_NEKO7 + COMPOSE=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.project.working_dir"}}}}' 2>/dev/null || true) + PROJ=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.project"}}}}' 2>/dev/null || true) + SVC=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.service"}}}}' 2>/dev/null || true) + echo COMPOSE=$COMPOSE PROJ=$PROJ SVC=$SVC + if [ -n "$COMPOSE" ] && [ -n "$SVC" ]; then + cd "$COMPOSE" + docker compose -p "$PROJ" up -d --force-recreate --no-deps "$SVC" + else + docker stop douyinweb-neko-7 || true + docker rm douyinweb-neko-7 || true + cd /opt/douyinWEB/backend + set -a; source /etc/douyinweb.env 2>/dev/null || true; set +a + ./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +print(yn.ensure_capacity(8, start_instances={{7}}, reconcile_running=True)) +PY + fi + sleep 12 +fi + +docker exec douyinweb-neko-7 grep -n 'no-turbofan\|PassageEmbeddings\|no-wasm-simd\|renderer-process-limit' /etc/neko/browser-launch.sh +docker exec douyinweb-neko-7 supervisorctl restart google-chrome +sleep 12 +docker exec douyinweb-neko-7 supervisorctl status google-chrome +docker exec douyinweb-neko-7 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "js-flags|turbofan|Passage|renderer-process|wasm|max-old"; break ;; + esac +done' + +# recover tabs: close crash junk, open studio or youtube home light +docker exec douyinweb-neko-7 python3 -c ' +import json, urllib.request, time +for i in range(40): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=2).read(); print("devtools_ok"); break + except Exception: + time.sleep(1) +else: + raise SystemExit("no_devtools") +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +for t in tabs: + if t.get("type")!="page": + continue + tid=t.get("id") or "" + url=t.get("url") or "" + title=t.get("title") or "" + # close Aw Snap / heavy youtube.com homepage spam; keep one studio if present + if tid and ("chrome-error://" in url or "Aw, Snap" in title or url.rstrip("/") in ("https://www.youtube.com","https://youtube.com","https://www.google.com")): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/close/"+tid, timeout=3).read() + print("CLOSE", title[:40], url[:80]) + except Exception as e: + print("close_err", e) +# prefer open studio livestreaming blank dashboard of creator studio +S="https://studio.youtube.com/" +req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") +try: + print("OPEN", urllib.request.urlopen(req, timeout=15).read()[:100]) +except Exception as e: + print("open_err", e) +time.sleep(5) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print("TAB", (t.get("title") or "")[:60], "|", (t.get("url") or "")[:110]) +' + +# oom protect neko chrome pids +for pid in $(docker top douyinweb-neko-7 -eo pid 2>/dev/null | awk "NR>1{{print \$1}}"); do + echo -800 > /proc/$pid/oom_score_adj 2>/dev/null || true +done +echo oom_adj_done +""", +) + +# --- 3) also patch all other running nekos' visible launch script + optional restart --- +run( + c, + rf""" +set +e +# sync file for future starts +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +# for each running neko, overwrite its mounted inode +for name in $(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}'); do + ino=$(docker exec "$name" sh -c 'ls -li /etc/neko/browser-launch.sh' 2>/dev/null | awk '{{print $1}}') + [ -z "$ino" ] && continue + match=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$ino" '$1==i {{print $NF; exit}}') + if [ -n "$match" ]; then + cat {tmp} > "$match" + echo patched_inode $name $match + fi + if ! docker exec "$name" grep -q no-turbofan /etc/neko/browser-launch.sh 2>/dev/null; then + echo STALE $name + else + echo OK_VISIBLE $name + fi +done +echo '=== mem ===' +free -h | head -3 +docker stats --no-stream --format '{{{{.Name}}}} {{{{.MemUsage}}}}' | head -20 +curl -sk -m 10 -o /dev/null -w 'pub_neko7:%{{http_code}}\n' https://dy.nomadro.live/neko/7/ +dmesg -T 2>/dev/null | grep -iE 'invalid opcode|oom-kill' | tail -5 +""", +) + +c.close() +print("DONE") diff --git a/scripts/_deploy_dylive_catchup.py b/scripts/_deploy_dylive_catchup.py new file mode 100644 index 0000000..30640fd --- /dev/null +++ b/scripts/_deploy_dylive_catchup.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Deploy pending dy features to dylive.nomadro.com. Never recreate Neko.""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOST = "107.173.30.245" + +FILES = [ + "backend/app/yt_stream_key_db.py", + "backend/app/yt_assign_db.py", + "backend/app/youtube_relay_status.py", + "backend/app/models.py", + "backend/app/main.py", + "backend/neko/browser-launch.sh", + "frontend/src/lib/ytRelayStatus.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/app/youtube-relay-log/page.tsx", +] + + +def connect(retries: int = 15): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + auth_timeout=60, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(4 + i * 2) + raise SystemExit(f"ssh_fail: {last}") + + +def run(c, cmd: str, t: int = 900) -> tuple[int, str]: + print(f"\n===== {cmd[:100].replace(chr(10), ' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return code, out + + +for rel in FILES: + assert (ROOT / rel).is_file(), rel + +c = connect() +code, before = run( + c, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; free -h | head -2", +) +before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln} +print("before_up", sorted(before_up), flush=True) + +# upload files +sftp = c.open_sftp() +for rel in FILES: + remote = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" + run(c, f"mkdir -p {'/'.join(remote.split('/')[:-1])}", t=30) + print("put", rel, flush=True) + sftp.put(str(ROOT / rel), remote) +sftp.close() + +# patch browser-launch into whatever inode running nekos mount +run( + c, + r""" +set +e +SRC=/opt/douyinWEB/backend/neko/browser-launch.sh +grep -n jitless "$SRC" | head -3 +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + ino=$(docker exec "$name" sh -c 'ls -li /etc/neko/browser-launch.sh' 2>/dev/null | awk '{print $1}') + [ -z "$ino" ] && continue + match=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$ino" '$1==i{print $NF; exit}') + if [ -n "$match" ]; then + cat "$SRC" > "$match" + echo patched "$name" "$match" + fi + if docker exec "$name" grep -q jitless /etc/neko/browser-launch.sh 2>/dev/null; then + echo OK_VISIBLE "$name" + else + echo STALE "$name" + fi +done +""", +) + +# API restart + import keys from assign + optional peer import from local export if we pull from dy later +run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_stream_key_db, yt_assign_db, models +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +print('groups', len(gs), 'with_stream_key', sum(1 for g in gs if g.get('stream_key'))) +print('import', yt_stream_key_db.import_from_assign_groups(replace=False)) +print('registry_total', yt_stream_key_db.list_entries(include_secret=False)['total']) +PY +systemctl restart douyinweb-api +sleep 5 +systemctl is-active douyinweb-api +curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 200; echo +""", +) + +# Frontend: prefer copying .next from local tarball if exists; else low-mem build +tgz = ROOT / "scripts" / "_dy_next_keys.tgz" +if tgz.is_file() and tgz.stat().st_size > 1_000_000: + print("upload next tarball", tgz.stat().st_size, flush=True) + sftp = c.open_sftp() + sftp.put(str(tgz), "/tmp/dy-next-keys.tgz") + sftp.close() + run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/frontend +mkdir -p .next +tar -xzf /tmp/dy-next-keys.tgz -C /opt/douyinWEB/frontend +# ensure source files exist too +test -f src/app/youtube/keys/page.tsx && echo keys_src_ok +systemctl restart douyinweb-web +sleep 4 +systemctl is-active douyinweb-web +""", + ) +else: + run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=1536 +# drop caches to help build +sync; echo 3 > /proc/sys/vm/drop_caches || true +if [ -d node_modules ]; then + npm run build +else + echo 'FATAL no node_modules' + exit 3 +fi +systemctl restart douyinweb-web +sleep 4 +systemctl is-active douyinweb-web +""", + t=900, + ) + +code, after = run( + c, + r""" +set +e +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +curl -sk -m 15 -o /dev/null -w 'home:%{http_code}\n' https://dylive.nomadro.com/ +curl -sk -m 15 -o /dev/null -w 'youtube:%{http_code}\n' https://dylive.nomadro.com/youtube +curl -sk -m 15 -o /dev/null -w 'keys:%{http_code}\n' https://dylive.nomadro.com/youtube/keys +# smoke login + groups have stream_key +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +print('login', op.open(req, timeout=20).status) +gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=60).read()).get('groups') or [] +print('groups', len(gs), 'key_fields', sum(1 for g in gs if g.get('stream_key'))) +keys=json.loads(op.open('http://127.0.0.1:8014/api/youtube/stream-keys', timeout=30).read()) +print('registry', keys.get('total')) +PY +""", +) +after_up = {ln.split()[0] for ln in after.splitlines() if " Up " in ln and "neko" in ln} +lost = before_up - after_up +if lost: + print("CRITICAL neko lost", lost, flush=True) + run(c, "docker start " + " ".join(sorted(lost)) + "; sleep 6; docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") + raise SystemExit(2) +print("neko_ok", sorted(after_up), flush=True) +c.close() +print("ALL_DONE") diff --git a/scripts/_deploy_dylive_latest_neko.py b/scripts/_deploy_dylive_latest_neko.py new file mode 100644 index 0000000..086257b --- /dev/null +++ b/scripts/_deploy_dylive_latest_neko.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Deploy latest origin/test1 to dylive VPS and force-recreate Neko containers.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +USER = "root" +PASSWORD = "Xiao4669805" +REPO = "/opt/douyinWEB" +REMOTE = "https://eric:Xiao4669805@gitea.dsx2020.com/eric/douyinWEB.git" +BRANCH = "test1" + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 600) -> tuple[int, str]: + print(f"\n$ {cmd[:240]}{'…' if len(cmd) > 240 else ''}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-8000:] if len(out) > 8000 else out, flush=True) + print(f"→ exit={code}", flush=True) + return code, out + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASSWORD, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False) + try: + ts = time.strftime("%Y%m%d_%H%M%S") + run( + c, + f"cd {REPO} && cp -a backend/data/monitor.db backend/data/monitor.db.bak.{ts} 2>/dev/null || true; " + f"ls -la backend/data/monitor.db | head -1", + timeout=30, + ) + + code, _ = run( + c, + f"set -e; cd {REPO}; " + f"git remote set-url origin '{REMOTE}'; " + f"git fetch origin {BRANCH}; " + f"git reset --hard HEAD; " + f"git clean -fd -e backend/data -e frontend/.next -e node_modules -e frontend/node_modules " + f"-e backend/.venv -e .venv -e '*.db' -e '*.db-*'; " + f"git checkout -f -B {BRANCH} origin/{BRANCH}; " + f"git reset --hard origin/{BRANCH}; " + f"git log -1 --oneline; git status -sb; " + f"test \"$(git rev-parse HEAD)\" = \"$(git rev-parse origin/{BRANCH})\"", + timeout=300, + ) + if code != 0: + print("FATAL: git sync failed", flush=True) + return 1 + + run( + c, + f"cd {REPO}/backend; " + f"(test -x .venv/bin/pip && .venv/bin/pip install -r requirements.txt -q) || " + f"(test -x ../.venv/bin/pip && ../.venv/bin/pip install -r requirements.txt -q) || true; " + f"chmod +x {REPO}/backend/neko/browser-launch.sh 2>/dev/null || true; " + f"sed -i 's/\\r$//' {REPO}/backend/neko/browser-launch.sh 2>/dev/null || true; " + f"echo deps_ok", + timeout=300, + ) + + run( + c, + "systemctl restart douyinweb-api douyinweb-pb douyinweb-yt 2>/dev/null || systemctl restart douyinweb-api; " + "sleep 3; systemctl is-active douyinweb-api", + timeout=90, + ) + + code, _ = run( + c, + f"set -e; cd {REPO}/frontend; npm ci --prefer-offline 2>/dev/null || npm install; npm run build", + timeout=900, + ) + if code != 0: + print("FATAL: frontend build failed", flush=True) + return 1 + + run(c, "systemctl restart douyinweb-web; sleep 2; systemctl is-active douyinweb-api douyinweb-web", timeout=90) + + # Force recreate Neko on VPS (allowed) + code, out = run( + c, + f"cd {REPO}/backend && .venv/bin/python - <<'PY'\n" + "from app import youtube_neko, yt_assign_db\n" + "groups = yt_assign_db.list_groups(include_urls=False)\n" + "print('groups', [(g.get('name'), g.get('neko_instance_id'), g.get('neko_enabled')) for g in groups])\n" + "print('desired', youtube_neko._desired_from_db())\n" + "print('docker', youtube_neko._docker_available())\n" + "r = youtube_neko.recreate_all_instances(start_enabled=True)\n" + "print('recreate', r)\n" + "PY", + timeout=1200, + ) + if code != 0: + print("WARN: neko recreate command failed", flush=True) + + run( + c, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' 2>/dev/null | head -30; " + "curl -sS -m 15 http://127.0.0.1:8014/api/health | head -c 500; echo; " + "curl -sS -m 20 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + f"cd {REPO} && git rev-parse --short HEAD && test -f backend/data/monitor.db && echo monitor_db=ok", + timeout=60, + ) + print("\nDONE dylive latest + neko recreate", flush=True) + return 0 + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_deploy_fe_evidence.py b/scripts/_deploy_fe_evidence.py new file mode 100644 index 0000000..61757c8 --- /dev/null +++ b/scripts/_deploy_fe_evidence.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Build FE on dy, ship .next to dylive — no pkill.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh {host} {i}", flush=True) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + return c + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + raise SystemExit("ssh_fail") + + +def run(c, cmd, timeout=700): + print(f"$ {cmd[:100]}...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + t0 = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - t0 > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.15) + code = chan.recv_exit_status() + print(f"\n[exit {code}]", flush=True) + return code + + +print("=== dy build ===", flush=True) +c = connect("108.174.50.68") +# ensure panel source present +sftp = c.open_sftp() +data = (ROOT / "frontend/src/components/YtRelayProStatusPanel.tsx").read_bytes() +with sftp.file("/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx", "wb") as f: + f.write(data) +sftp.close() +code = run( + c, + r""" +set -e +cd /opt/douyinWEB/frontend +grep -n '若 Live 开在远程' src/components/YtRelayProStatusPanel.tsx | head -3 +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build +systemctl restart douyinweb-web +echo web=$(systemctl is-active douyinweb-web) +tar -C /opt/douyinWEB/frontend -czf /tmp/next-evidence.tgz .next +ls -lh /tmp/next-evidence.tgz +""", + timeout=700, +) +if code != 0: + raise SystemExit(f"build_fail {code}") +print("fetch...", flush=True) +sftp = c.open_sftp() +sftp.get("/tmp/next-evidence.tgz", str(ROOT / "scripts/_next-evidence.tgz")) +sftp.close() +c.close() + +print("=== dylive apply ===", flush=True) +c = connect("107.173.30.245") +sftp = c.open_sftp() +local = ROOT / "scripts/_next-evidence.tgz" +last = [0.0] + +def cb(sent, total): + now = time.time() + if now - last[0] >= 2 or sent == total: + print(f" upload {100*sent/total:.0f}%", flush=True) + last[0] = now + +sftp.put(str(local), "/tmp/next-evidence.tgz", callback=cb) +# also panel src +with sftp.file("/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx", "wb") as f: + f.write(data) +sftp.close() +run( + c, + r""" +set -e +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_ev +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_ev 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-evidence.tgz +systemctl start douyinweb-web +sleep 2 +echo web=$(systemctl is-active douyinweb-web) +""", + timeout=120, +) +c.close() +print("FE_DONE", flush=True) diff --git a/scripts/_deploy_graceful_end_stream.py b/scripts/_deploy_graceful_end_stream.py new file mode 100644 index 0000000..f31ad36 --- /dev/null +++ b/scripts/_deploy_graceful_end_stream.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Deploy graceful End Stream path to dylive.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-18000:] if len(out) > 18000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +for rel, remote in [ + ("backend/neko/cdp_end_stream.py", "/tmp/cdp_end_stream.py"), + ("backend/app/youtube_neko.py", "/tmp/youtube_neko.py"), + ("backend/app/youtube_manage.py", "/tmp/youtube_manage.py"), + ("backend/app/youtube_relay_pipeline.py", "/tmp/youtube_relay_pipeline.py"), +]: + sftp.put(str(ROOT / rel), remote) +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail +install -m 0644 /tmp/cdp_end_stream.py /opt/douyinWEB/backend/neko/cdp_end_stream.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/youtube_manage.py /opt/douyinWEB/backend/app/youtube_manage.py +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +cd /opt/douyinWEB/backend +./.venv/bin/python -m py_compile app/youtube_neko.py app/youtube_manage.py app/youtube_relay_pipeline.py neko/cdp_end_stream.py +./.venv/bin/python - <<'PY' +from app import youtube_neko, youtube_manage, youtube_relay_pipeline +assert hasattr(youtube_neko, "cdp_end_studio_stream") +assert hasattr(youtube_neko, "end_live_session") +assert hasattr(youtube_manage, "complete_active_live_broadcast") +assert hasattr(youtube_relay_pipeline.youtube_relay_pipeline, "_graceful_retire_group") +print("symbols_ok") +PY +systemctl restart douyinweb-api +for i in $(seq 1 45); do curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break; sleep 1; done +curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 200; echo +echo DONE +""", +) +c.close() +raise SystemExit(code) diff --git a/scripts/_deploy_http_live_final.py b/scripts/_deploy_http_live_final.py new file mode 100644 index 0000000..cfe530d --- /dev/null +++ b/scripts/_deploy_http_live_final.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +DATA = (ROOT / "backend" / "app" / "youtube_live.py").read_bytes() + +VERIFY = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live +youtube_live._LAST_OAUTH_AT = 0.0 +async def main(): + for cid, name in [ + ("UCXFErW9DeE8EXrInlnyCnVw", "asian"), + ("UCYnwXkCMmVFf8Vr6MlWb-Jw", "hack"), + ("UCf-uYs6f5yg3iWylnHkIKug", "nomadSF"), + ]: + r = youtube_live._http_channel_live_probe(cid) + print("http", name, "live", r.get("is_live"), "err", (r.get("error") or "-")[:80], "url", (r.get("live_url") or "-")[:60]) + m = await youtube_live.build_live_map(force=True) + live = [ + (k, v.get("source"), (v.get("title") or "")[:36], (v.get("live_url") or "")[:55]) + for k, v in (m.get("entries") or {}).items() + if v.get("is_live") and str(k).startswith("assign:") + ] + print("live_count", m.get("live_count"), "assign_live", len(live), "map_source", m.get("source")) + for row in live: + print(" LIVE", row) +asyncio.run(main()) +''' + + +def run(c, cmd, t=180): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return str(ex) + + +def deploy(host, port, user, pw, sudo=False): + print(f"\n===== {user}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_yl3.py", "wb") as f: + f.write(DATA) + with sftp.file("/tmp/_v3.py", "w") as f: + f.write(VERIFY) + sftp.close() + dst = "/opt/douyinWEB/backend/app/youtube_live.py" + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat /tmp/_yl3.py > {dst}; systemctl restart douyinweb-api\"", 50) + else: + run(c, f"cat /tmp/_yl3.py > {dst}; systemctl restart douyinweb-api >/tmp/r.log 2>&1 &", 15) + for i in range(12): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print("health", h) + if h == "200": + break + if i == 5 and not sudo: + run(c, "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", 30) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_v3.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 220)[:3000]) + c.close() + + +def main(): + deploy("107.173.30.245", 22, "root", "Xiao4669805", False) + deploy("107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_http_live_fix.py b/scripts/_deploy_http_live_fix.py new file mode 100644 index 0000000..5259616 --- /dev/null +++ b/scripts/_deploy_http_live_fix.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy http_live fix + youtube-svc /live resolve; verify 3 lives.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + ("backend/app/youtube_live.py", "/opt/douyinWEB/backend/app/youtube_live.py"), + ("youtube-svc/src/youtube.mjs", "/opt/douyinWEB/youtube-svc/src/youtube.mjs"), +] + +VERIFY = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live +youtube_live._LAST_OAUTH_AT = 0.0 +async def main(): + m = await youtube_live.build_live_map(force=True) + live = [(k, v.get("source"), (v.get("title") or "")[:40], v.get("live_url","")[:60]) + for k,v in (m.get("entries") or {}).items() if v.get("is_live") and str(k).startswith("assign:")] + print("live_count", m.get("live_count"), "source", m.get("source")) + print("assign_live", len(live)) + for row in live: + print(" LIVE", row) +asyncio.run(main()) +''' + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def deploy(host, port, user, pw, sudo=False): + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for rel, dst in FILES: + tmp = f"/tmp/_fix_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((ROOT / rel).read_bytes()) + if sudo: + print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat {tmp} > {dst}\"", 30).strip()) + else: + # youtube-svc path may need mkdir + print(run(c, f"mkdir -p $(dirname {dst}); cat {tmp} > {dst} && echo OK {dst}", 20).strip()) + with sftp.file("/tmp/_verify_http_live.py", "w") as f: + f.write(VERIFY) + sftp.close() + # restart api + yt svc + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' systemctl restart douyinweb-yt douyinweb-api", 50) + else: + run(c, "systemctl restart douyinweb-yt >/tmp/_yt.txt 2>&1 || true", 20) + run(c, "systemctl restart douyinweb-api >/tmp/_api.txt 2>&1 &", 10) + for i in range(12): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print(f" try{i} {h}") + if h == "200": + break + if i == 5 and not sudo: + run(c, "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", 30) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_http_live.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 200)[:2500]) + c.close() + + +def main(): + deploy("107.173.30.245", 22, "root", "Xiao4669805", False) + deploy("107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_http_live_proxy.py b/scripts/_deploy_http_live_proxy.py new file mode 100644 index 0000000..117e0b8 --- /dev/null +++ b/scripts/_deploy_http_live_proxy.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +DATA = (ROOT / "backend" / "app" / "youtube_live.py").read_bytes() + +VERIFY = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live +print("PROXY", os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "-") +# physical often only sets proxy on douyinweb-yt; fall back to ShellCrash +if not (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")): + os.environ["HTTPS_PROXY"] = "http://127.0.0.1:7890" + os.environ["HTTP_PROXY"] = "http://127.0.0.1:7890" + print("PROXY_FALLBACK", os.environ["HTTPS_PROXY"]) +youtube_live._LAST_OAUTH_AT = 0.0 +async def main(): + for cid, name in [ + ("UCXFErW9DeE8EXrInlnyCnVw", "asian"), + ("UCYnwXkCMmVFf8Vr6MlWb-Jw", "hack"), + ("UCf-uYs6f5yg3iWylnHkIKug", "nomadSF"), + ]: + r = youtube_live._http_channel_live_probe(cid) + print("http", name, "live", r.get("is_live"), "err", (r.get("error") or "")[:70], "url", (r.get("live_url") or "")[:55]) + m = await youtube_live.build_live_map(force=True) + live = [ + (k, v.get("source"), (v.get("title") or "")[:36]) + for k, v in (m.get("entries") or {}).items() + if v.get("is_live") and str(k).startswith("assign:") + ] + print("live_count", m.get("live_count"), "assign_live", len(live)) + for row in live: + print(" ", row) +asyncio.run(main()) +''' + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return str(ex) + + +def deploy(host, port, user, pw, sudo=False): + print(f"\n===== {user}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_yl2.py", "wb") as f: + f.write(DATA) + with sftp.file("/tmp/_v2.py", "w") as f: + f.write(VERIFY) + sftp.close() + dst = "/opt/douyinWEB/backend/app/youtube_live.py" + if sudo: + print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat /tmp/_yl2.py > {dst}; systemctl restart douyinweb-api\"", 50)) + else: + print(run(c, f"cat /tmp/_yl2.py > {dst}; systemctl restart douyinweb-api >/tmp/r.log 2>&1 &", 15)) + for i in range(12): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print("health", h) + if h == "200": + break + if i == 5 and not sudo: + run(c, "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", 30) + print(run(c, "systemctl show douyinweb-api -p Environment --no-pager | head -c 500")) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_v2.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 200)[:2500]) + c.close() + + +def main(): + deploy("107.173.30.245", 22, "root", "Xiao4669805", False) + deploy("107.173.30.245", 4014, "eric", "4669805", True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_key_visible_dylive_only.py b/scripts/_deploy_key_visible_dylive_only.py new file mode 100644 index 0000000..f7e93d1 --- /dev/null +++ b/scripts/_deploy_key_visible_dylive_only.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""dylive-only: upload key-visible files, restart API, copy .next from local tgz if present / skip heavy build.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +FILES = [ + "backend/app/yt_assign_db.py", + "backend/app/yt_stream_key_db.py", + "backend/app/youtube_relay_status.py", + "backend/app/main.py", + "frontend/src/lib/ytRelayStatus.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/app/youtube-relay-log/page.tsx", +] + + +def connect(): + last = None + for i in range(15): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + last = e + print("retry", i, e, flush=True) + time.sleep(5 + i * 2) + raise SystemExit(last) + + +c = connect() +_i, o, e = c.exec_command( + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; free -h | head -2", + timeout=60, +) +before = (o.read() + e.read()).decode() +print("BEFORE\n", before, flush=True) + +sftp = c.open_sftp() +for rel in FILES: + remote = f"/opt/douyinWEB/{rel}" + _i, o, e = c.exec_command(f"mkdir -p {'/'.join(remote.split('/')[:-1])}", timeout=30) + o.channel.recv_exit_status() + print("put", rel, flush=True) + sftp.put(str(ROOT / rel), remote) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import yt_assign_db; gs=yt_assign_db.list_groups(include_urls=False, include_secret=True); print("keys", sum(1 for g in gs if g.get("stream_key")))' +systemctl restart douyinweb-api +sleep 5 +systemctl is-active douyinweb-api +# Avoid next build OOM — only restart web (src already updated; if build missing keys route, page may 404 until later build) +systemctl restart douyinweb-web +sleep 3 +systemctl is-active douyinweb-web +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +curl -sk -o /dev/null -w 'keys:%{http_code}\n' https://dylive.nomadro.com/youtube/keys +""", + timeout=120, +) +print((o.read() + e.read()).decode(), flush=True) +c.close() +print("DONE_DYLIVE") diff --git a/scripts/_deploy_live_count_fix.py b/scripts/_deploy_live_count_fix.py new file mode 100644 index 0000000..9cd658e --- /dev/null +++ b/scripts/_deploy_live_count_fix.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Deploy live-map overcount fix (edge_assign_live sticky 在播).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/app/youtube_live.py"), "/tmp/youtube_live.py") +sftp.put(str(ROOT / "backend/tests/test_youtube_live.py"), "/tmp/test_youtube_live.py") +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail +install -m 0644 /tmp/youtube_live.py /opt/douyinWEB/backend/app/youtube_live.py +install -m 0644 /tmp/test_youtube_live.py /opt/douyinWEB/backend/tests/test_youtube_live.py +cd /opt/douyinWEB/backend +./.venv/bin/python -m py_compile app/youtube_live.py +./.venv/bin/python -m pytest -q tests/test_youtube_live.py +systemctl restart douyinweb-api.service +sleep 4 +systemctl is-active douyinweb-api.service +./.venv/bin/python - <<'PY' +import asyncio, json, time +from app import youtube_live +from app.youtube_relay_pipeline import youtube_relay_pipeline as pipe + +m = asyncio.run(youtube_live.build_live_map(force=True)) +print("live_count", m.get("live_count"), "age", round(time.time()-float(m.get("checked_at") or 0),1)) +lives=[] +for k,v in (m.get("entries") or {}).items(): + if not (k.startswith("assign:") and v.get("is_live")): + continue + st=v.get("studio") if isinstance(v.get("studio"), dict) else {} + lives.append({ + "key": k[:40], + "title": v.get("title"), + "source": v.get("source"), + "studio_src": (st or {}).get("detect_source"), + "on_air": (st or {}).get("on_air"), + "status": (st or {}).get("live_status"), + }) +print(json.dumps(lives, ensure_ascii=False, indent=2)) +st=pipe.status() +push=[(r.get("name"), r.get("business_status"), r.get("is_pushing")) for r in (st.get("groups") or []) if r.get("is_pushing") or r.get("business_status") in {"streaming","relay_slow"}] +print("pushing", push) +PY +""", +) +c.close() +raise SystemExit(code) diff --git a/scripts/_deploy_live_probe_tighten.py b/scripts/_deploy_live_probe_tighten.py new file mode 100644 index 0000000..3613962 --- /dev/null +++ b/scripts/_deploy_live_probe_tighten.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy tightened live probes (http_live + youtube.mjs) to VPS + physical.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +YL = (ROOT / "backend" / "app" / "youtube_live.py").read_bytes() +YT = (ROOT / "youtube-svc" / "src" / "youtube.mjs").read_bytes() + +VERIFY = r''' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", +) +print("login", op.open(req, timeout=15).status) +raw=op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=120).read() +p=json.loads(raw) +print("live_count", p.get("live_count"), "source", p.get("source"), "svc", (p.get("svc_error") or "")[:80]) +for k,v in sorted((p.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", k, v.get("source"), (v.get("title") or "")[:36], (v.get("live_url") or "")[:70]) +# also http probe via venv +import os,sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0,".") +from app import youtube_live +for cid,name in [ + ("UCXFErW9DeE8EXrInlnyCnVw","asian_UCXF"), + ("UCjQ8jnBm2N4FGRowNXcXThw","asian_UCjQ"), + ("UCYnwXkCMmVFf8Vr6MlWb-Jw","hack"), + ("UCf-uYs6f5yg3iWylnHkIKug","nomadSF"), +]: + r=youtube_live._http_channel_live_probe(cid) + print("http", name, "live", r.get("is_live"), "title", (r.get("title") or "")[:40], "err", (r.get("error") or "-")[:60]) +''' + + +def run(c, cmd, t=180): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return str(ex) + + +def deploy(host, port, user, pw, sudo=False): + print(f"\n===== {user}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_yl_fix.py", "wb") as f: + f.write(YL) + with sftp.file("/tmp/_yt_fix.mjs", "wb") as f: + f.write(YT) + with sftp.file("/tmp/_v_live.py", "w") as f: + f.write(VERIFY) + sftp.close() + yl = "/opt/douyinWEB/backend/app/youtube_live.py" + yt = "/opt/douyinWEB/youtube-svc/src/youtube.mjs" + if sudo: + run( + c, + f"echo '{pw}' | sudo -S -p '' bash -lc \"cat /tmp/_yl_fix.py > {yl}; cat /tmp/_yt_fix.mjs > {yt}; " + f"systemctl restart douyinweb-yt; systemctl restart douyinweb-api\"", + 60, + ) + else: + run(c, f"cat /tmp/_yl_fix.py > {yl}; cat /tmp/_yt_fix.mjs > {yt}", 20) + run(c, "systemctl restart douyinweb-yt; systemctl restart douyinweb-api >/tmp/r.log 2>&1 &", 15) + for i in range(14): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print("health", h) + if h == "200": + break + if i == 6 and not sudo: + run( + c, + "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", + 30, + ) + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_v_live.py" + if sudo: + py = f"echo '{pw}' | sudo -S -p '' {py}" + print(run(c, py, 240)[:4000]) + c.close() + + +if __name__ == "__main__": + deploy("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("107.173.30.245", 4014, "eric", "4669805", sudo=True) diff --git a/scripts/_deploy_neko_enable_switch_ux.py b/scripts/_deploy_neko_enable_switch_ux.py new file mode 100644 index 0000000..a2879fe --- /dev/null +++ b/scripts/_deploy_neko_enable_switch_ux.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy Neko enable-switch sync + toggle UX (no global busy freeze).""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] +FILES = [ + "frontend/src/components/EnableSwitch.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/app/shorts/page.tsx", + "frontend/src/app/yt-long/page.tsx", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_es.tsx','/opt/douyinWEB/frontend/src/components/EnableSwitch.tsx'), + ('/tmp/_yrpsp.tsx','/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx'), + ('/tmp/_yap.tsx','/opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx'), + ('/tmp/_shorts.tsx','/opt/douyinWEB/frontend/src/app/shorts/page.tsx'), + ('/tmp/_ytlong.tsx','/opt/douyinWEB/frontend/src/app/yt-long/page.tsx'), +] +for s,d in pairs: + data=Path(s).read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n') + Path(d).write_bytes(data) + print('ok', d, len(data)) +text=Path('/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx').read_text(encoding='utf-8') +assert 'nekoPowerOn' in text +assert 'Optimistic' in text or 'optimistic' in text.lower() or 'Optimistic' in text +print('assert_ok') +PY +cd /opt/douyinWEB/frontend +npm run build 2>&1 | tail -40 +systemctl restart douyinweb-web.service +sleep 2 +systemctl is-active douyinweb-web.service +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + mapping = [ + (FILES[0], "/tmp/_es.tsx"), + (FILES[1], "/tmp/_yrpsp.tsx"), + (FILES[2], "/tmp/_yap.tsx"), + (FILES[3], "/tmp/_shorts.tsx"), + (FILES[4], "/tmp/_ytlong.tsx"), + ] + for rel, remote in mapping: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_deploy_neko_switch_ux.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_neko_switch_ux.sh", timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace")[-5000:], flush=True) + c.close() + + +def main(): + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_neko_mem_limit.py b/scripts/_deploy_neko_mem_limit.py new file mode 100644 index 0000000..a0a715e --- /dev/null +++ b/scripts/_deploy_neko_mem_limit.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Deploy Neko mem_limit (1536m) without recreating containers / touching Chrome profiles. + +Uses `docker update` so running Studio + Google login stay intact. +""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + last = None + for i in range(6): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as ex: + last = ex + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit(last) + + +def run(c, cmd, t=360): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/app/youtube_neko.py"), "/tmp/youtube_neko.py") +sftp.put(str(ROOT / "backend/app/config.py"), "/tmp/config.py") +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail +# --- BEFORE: fingerprint login profile (must not change) --- +PROF12=/opt/douyinWEB/backend/data/neko/profiles/12 +echo '=== BEFORE profile12 fingerprint ===' +ls -la "$PROF12/Default/Cookies" "$PROF12/Default/Login Data" 2>/dev/null || ls -la "$PROF12/Default/" | head -20 +python3 - <<'PY' +from pathlib import Path +p=Path("/opt/douyinWEB/backend/data/neko/profiles/12/Default") +for name in ("Cookies","Login Data","Preferences"): + f=p/name + if f.exists(): + st=f.stat() + print(f"{name}\tsize={st.st_size}\tmtime={int(st.st_mtime)}") + else: + print(f"{name}\tMISSING") +open("/tmp/neko12_fp_before.txt","w").write( + "\n".join( + f"{n}\t{(p/n).stat().st_size if (p/n).exists() else -1}" + for n in ("Cookies","Login Data") + ) +) +PY + +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/config.py /opt/douyinWEB/backend/app/config.py + +systemctl restart douyinweb-api +for i in $(seq 1 45); do + curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break + sleep 1 +done +curl -sS -m 5 http://127.0.0.1:8014/api/health || true + +# Rewrite compose YAML only (no force-recreate — preserve Chrome) +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import youtube_neko +# desired from DB assignments; do not start/stop +d = max(youtube_neko._desired_from_db(), 12) +r = youtube_neko.ensure_capacity(d, start_instances=set(), reconcile_running=False) +print(r) +# show mem_limit lines landed in compose +text = youtube_neko._compose_path().read_text(encoding="utf-8") +print("mem_limit_lines", sum(1 for ln in text.splitlines() if "mem_limit" in ln)) +print([ln.strip() for ln in text.splitlines() if "mem" in ln.lower()][:8]) +PY + +# Live apply hard cap WITHOUT recreate (login/tabs stay) +echo '=== docker update mem on all neko containers ===' +for name in $(docker ps -a --filter name=douyinweb-neko- --format '{{.Names}}'); do + echo "update $name" + docker update --memory 1536m --memory-swap 1536m "$name" +done + +echo '=== AFTER limits ===' +docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}' $(docker ps -q --filter name=douyinweb-neko) 2>/dev/null || true +docker inspect douyinweb-neko-12 --format 'Memory={{.HostConfig.Memory}} MemorySwap={{.HostConfig.MemorySwap}}' || true + +echo '=== AFTER profile12 fingerprint ===' +python3 - <<'PY' +from pathlib import Path +p=Path("/opt/douyinWEB/backend/data/neko/profiles/12/Default") +for name in ("Cookies","Login Data","Preferences"): + f=p/name + if f.exists(): + st=f.stat() + print(f"{name}\tsize={st.st_size}\tmtime={int(st.st_mtime)}") + else: + print(f"{name}\tMISSING") +before=Path("/tmp/neko12_fp_before.txt").read_text().strip().splitlines() +after={n: ((p/n).stat().st_size if (p/n).exists() else -1) for n in ("Cookies","Login Data")} +ok=True +for line in before: + n,s=line.split("\t") + if after.get(n)!=int(s): + print("MISMATCH", n, "before", s, "after", after.get(n)) + ok=False +print("LOGIN_FILES_INTACT" if ok else "LOGIN_FILES_CHANGED") +PY + +free -h +echo DONE +""", + t=240, +) + +c.close() +raise SystemExit(code) diff --git a/scripts/_deploy_neko_start_fix.py b/scripts/_deploy_neko_start_fix.py new file mode 100644 index 0000000..53e73e9 --- /dev/null +++ b/scripts/_deploy_neko_start_fix.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Deploy youtube_neko start-fix + recreate stale dylive containers.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + last = None + for i in range(6): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as ex: + last = ex + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit(last) + + +def run(c, cmd, t=360): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/app/youtube_neko.py"), "/tmp/youtube_neko.py") +sftp.put(str(ROOT / "backend/app/host_profile.py"), "/tmp/host_profile.py") +sftp.close() + +run( + c, + r""" +set +e +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/host_profile.py /opt/douyinWEB/backend/app/host_profile.py +# drop stale containers without published ports +docker rm -f douyinweb-neko-3 douyinweb-neko-7 douyinweb-neko-8 2>/dev/null +systemctl restart douyinweb-api +for i in $(seq 1 40); do + curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break + sleep 1 +done +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 20 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups | python3 -c ' +import sys,json +rows=json.load(sys.stdin) +rows=rows if isinstance(rows,list) else rows.get("groups") or [] +open("/tmp/en.txt","w").write("\n".join( + f"{g[\"id\"]} {int(g.get(\"neko_instance_id\") or 0)}" + for g in rows if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0)>0 +)) +print(open("/tmp/en.txt").read()) +' +while read -r GID NID; do + [[ -z "$GID" ]] && continue + echo "=== start $NID ===" + curl -sS -m 300 -b "$CS" -X POST "http://127.0.0.1:8014/api/youtube/assign/groups/${GID}/neko" \ + -H 'Content-Type: application/json' \ + -d '{"action":"start","enabled":true}' | python3 -c ' +import sys,json +d=json.load(sys.stdin) +n=d.get("neko") or {} +print({k:n.get(k) for k in ("id","running","ready","status","message","studio_url")}) +print("err", d.get("detail") or d.get("error")) +' +done < /tmp/en.txt +sleep 2 +docker ps --format '{{.Names}} {{.Status}} {{.Ports}}' | grep douyinweb-neko +ss -lntp | grep -E ':(920[0-7])\b' | head +for p in 9202 9206; do curl -sS -m 5 -o /dev/null -w "p$p=%{http_code}\n" http://127.0.0.1:$p/; done +# host profile effects via API +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/ops/host-profile | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("effects",{}).get("vps"))' +rm -f "$CS" +""", + 360, +) +c.close() + +with httpx.Client(follow_redirects=False, timeout=25) as cl: + for u in [ + "https://dylive.nomadro.com/neko/3/", + "https://dylive.nomadro.com/neko/7/", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(u) + print(f"{r.status_code} {u}", flush=True) + except Exception as ex: + print(f"ERR {u} {ex}", flush=True) +print("DONE", flush=True) diff --git a/scripts/_deploy_neko_ui_simplify.py b/scripts/_deploy_neko_ui_simplify.py new file mode 100644 index 0000000..706780b --- /dev/null +++ b/scripts/_deploy_neko_ui_simplify.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +"""Deploy simplified Neko button row (FE only).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = ["frontend/src/components/YtRelayProStatusPanel.tsx"] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_neko_ui_${i}.path" ]; do + rel=$(cat "/tmp/_dy_neko_ui_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_neko_ui_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done +cd "$ROOT/frontend" +npm run build >/tmp/dy_neko_ui_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -40 /tmp/dy_neko_ui_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 2 +systemctl is-active douyinweb-web.service +grep -nE '另开本机|启动本机 Neko|去配对远程|打开工作室' "$ROOT/frontend/src/components/YtRelayProStatusPanel.tsx" | head -20 +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_neko_ui_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_neko_ui_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_neko_ui_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_neko_ui_remote.sh" if sudo else "bash /tmp/_dy_neko_ui_remote.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("done") diff --git a/scripts/_deploy_nodata_on_air_gate.py b/scripts/_deploy_nodata_on_air_gate.py new file mode 100644 index 0000000..9f8f208 --- /dev/null +++ b/scripts/_deploy_nodata_on_air_gate.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy nodata/on_air gate fix to VPS + physical; stop invalid push; no profile wipe.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/neko/cdp_studio_scrape.py", + "backend/neko/live-ops-extension/content.js", +] + + +def put_tree(sftp, local: Path, remote: str) -> None: + data = local.read_bytes() + # write to /tmp then sudo install keeps perms + tmp = f"/tmp/_deploy_{local.name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + return tmp + + +def deploy_host(host, port, user, pw, sudo: bool) -> None: + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + sftp = c.open_sftp() + tmps = [] + for rel in FILES: + local = ROOT / rel + tmp = f"/tmp/_dyfix_{rel.replace('/', '_')}" + with sftp.file(tmp, "wb") as f: + f.write(local.read_bytes()) + tmps.append((tmp, f"/opt/douyinWEB/{rel}")) + print("upload", rel, local.stat().st_size) + sftp.close() + + lines = ["set -e"] + for tmp, dst in tmps: + lines.append(f"cp -a '{dst}' '{dst}.bak.nodata_$(date +%Y%m%d_%H%M%S)' 2>/dev/null || true") + # in-place for bind-mounted files + lines.append(f"cat '{tmp}' > '{dst}'") + lines.append(f"chmod --reference='{dst}.bak.nodata_'* '{dst}' 2>/dev/null || chmod 644 '{dst}'") + lines.append("echo FILES_OK") + body = "\n".join(lines) + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {body!r}" + else: + cmd = f"bash -lc {body!r}" + # body!r may break — use script file + sftp = c.open_sftp() + with sftp.file("/tmp/_deploy_nodata_gate.sh", "w") as f: + f.write("#!/bin/bash\nset -e\n") + for tmp, dst in tmps: + f.write(f"test -f '{dst}' || mkdir -p \"$(dirname '{dst}')\"\n") + f.write(f"cp -a '{dst}' \"{dst}.bak.nodata_$(date +%Y%m%d_%H%M%S)\" 2>/dev/null || true\n") + f.write(f"cat '{tmp}' > '{dst}'\n") + f.write(f"echo updated {dst}\n") + f.write("systemctl restart douyinweb-api || systemctl restart douyinweb || true\n") + f.write("sleep 2\n") + f.write("systemctl is-active douyinweb-api || systemctl is-active douyinweb || true\n") + sftp.close() + run = ( + f"echo '{pw}' | sudo -S -p '' bash /tmp/_deploy_nodata_gate.sh" + if sudo + else "bash /tmp/_deploy_nodata_gate.sh" + ) + _i, o, e = c.exec_command(run, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def stop_invalid_vps() -> None: + print("\n===== stop invalid push on VPS =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + script = r""" +python3 - <<'PY' +import sqlite3, time, signal, os +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +r=con.execute('select * from yt_relay_states where group_id=?',(gid,)).fetchone() +if r: + d=dict(r) + print('before', d.get('status'), 'pid', d.get('ffmpeg_pid'), 'push_sec', d.get('push_seconds')) + pid=int(d.get('ffmpeg_pid') or 0) + if pid>0: + try: + os.kill(pid, signal.SIGTERM) + print('killed', pid) + except Exception as e: + print('kill_err', e) + now=time.time() + con.execute("update yt_relay_states set status=?, error=?, ffmpeg_pid=0, updated_at=? where group_id=?", + ('waiting','手动停止:Studio 仍为 NODATA/待开播(未 on_air)的无效推流', now, gid)) + con.commit() + print('db set waiting') +else: + print('no state') +# also kill any leftover ffmpeg for youtube rtmp +import subprocess +out=subprocess.check_output("ps -ef | grep -E '[f]fmpeg.*rtmp' || true", shell=True, text=True) +print(out[:500]) +PY +systemctl restart douyinweb-api +sleep 3 +systemctl is-active douyinweb-api +curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 120; echo +""" + sftp = c.open_sftp() + with sftp.file("/tmp/_stop_invalid_push.sh", "w") as f: + f.write(script) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_stop_invalid_push.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def main() -> None: + deploy_host("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy_host("107.173.30.245", 4014, "eric", "4669805", sudo=True) + stop_invalid_vps() + print( + "\nNOTE: live-ops content.js is bind-mounted; next Studio navigation picks up nodata signals. " + "No Chrome restart (protect login)." + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_normal_auto_exclusive_dual.py b/scripts/_deploy_normal_auto_exclusive_dual.py new file mode 100644 index 0000000..200d50d --- /dev/null +++ b/scripts/_deploy_normal_auto_exclusive_dual.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""Deploy normal-auto + exclusive sticky + remove slots UI to dy then dylive. + +Build Next on dy (more RAM), copy .next tarball to dylive. Never recreate Neko. +""" +from __future__ import annotations + +import io +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +DY = "108.174.50.68" +DYLIVE = "107.173.30.245" + +FILES = [ + "backend/app/youtube_relay_pipeline.py", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayOpsHero.tsx", +] + + +def connect(host: str, retries: int = 12): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail {host}: {last}") + + +def run(c, cmd: str, t: int = 1200) -> tuple[int, str]: + print(f"\n===== {cmd[:120].replace(chr(10), ' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +def put_text(sftp, local: Path, remote: str) -> None: + raw = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(raw) + + +for rel in FILES: + assert (ROOT / rel).is_file(), rel + +# ---------- dy: upload + API restart + Next build ---------- +print("=== DY deploy ===", flush=True) +dy = connect(DY) +run( + dy, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; free -h | head -2", +) +sftp = dy.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +sftp.close() + +code, _ = run( + dy, + r""" +set -euo pipefail +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/YtRelayOpsHero.tsx /opt/douyinWEB/frontend/src/components/YtRelayOpsHero.tsx +# syntax check +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import youtube_relay_pipeline as p; print("import_ok", hasattr(p, "_claim_first_live_normal"))' +systemctl restart douyinweb-api +sleep 3 +systemctl is-active douyinweb-api +# build FE (dy has RAM) +cd /opt/douyinWEB/frontend +NODE_OPTIONS='--max-old-space-size=1536' npm run build +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +# pack .next for dylive +rm -f /tmp/dy_next_normal_auto.tgz +tar -C /opt/douyinWEB/frontend -czf /tmp/dy_next_normal_auto.tgz .next +ls -lh /tmp/dy_next_normal_auto.tgz +# smoke +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' | head -c 120; echo +curl -sS -m 15 -b "$CS" -o /dev/null -w 'youtube:%{http_code}\n' http://127.0.0.1:4015/youtube +# grep built chunk for new copy +grep -Rnl '单路独占' /opt/douyinWEB/frontend/.next/static 2>/dev/null | head -3 || true +grep -n '_claim_first_live_normal\|时间段排班 OFF' /opt/douyinWEB/backend/app/youtube_relay_pipeline.py | head -5 +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +echo DY_DONE +""", + t=1800, +) +if code != 0: + dy.close() + raise SystemExit(f"dy deploy failed: {code}") + +# download tarball via sftp to local then upload to dylive (or pipe) +print("=== transfer .next to local buffer ===", flush=True) +sftp = dy.open_sftp() +buf = io.BytesIO() +sftp.getfo("/tmp/dy_next_normal_auto.tgz", buf) +sftp.close() +dy.close() +print(f"tarball bytes={buf.tell()}", flush=True) + +# ---------- dylive ---------- +print("=== DYLIVE deploy ===", flush=True) +dl = connect(DYLIVE) +run( + dl, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; free -h | head -2", +) +sftp = dl.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +buf.seek(0) +with sftp.file("/tmp/dy_next_normal_auto.tgz", "wb") as f: + f.write(buf.getvalue()) +sftp.close() + +code, _ = run( + dl, + r""" +set -euo pipefail +# snapshot running nekos — must stay (start only if we touch nothing about recreate) +BEFORE=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort | tr '\n' ' ') +echo BEFORE_NEKO=$BEFORE + +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/YtRelayOpsHero.tsx /opt/douyinWEB/frontend/src/components/YtRelayOpsHero.tsx +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import youtube_relay_pipeline as p; print("import_ok", hasattr(p, "_claim_first_live_normal"))' +systemctl restart douyinweb-api +sleep 3 +systemctl is-active douyinweb-api + +# extract FE build — no npm build on 3.8G +cd /opt/douyinWEB/frontend +rm -rf .next.bak-normal-auto +if [ -d .next ]; then mv .next .next.bak-normal-auto; fi +tar -xzf /tmp/dy_next_normal_auto.tgz +test -d .next +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web + +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' | head -c 120; echo +curl -sS -m 15 -b "$CS" -o /dev/null -w 'youtube:%{http_code}\n' http://127.0.0.1:4015/youtube + +AFTER=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort | tr '\n' ' ') +echo AFTER_NEKO=$AFTER +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +free -h | head -2 +echo DYLIVE_DONE +""", + t=300, +) +dl.close() +if code != 0: + raise SystemExit(f"dylive deploy failed: {code}") + +# public smoke +import json +import ssl +import urllib.request +from http.cookiejar import CookieJar + +CTX = ssl.create_default_context() + + +def smoke(base: str): + cj = CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with op.open(req, timeout=45) as r: + print(base, "login", r.status) + with op.open(base + "/youtube", timeout=45) as r: + body = r.read().decode("utf-8", "replace") + print(base, "youtube", r.status, "独占" in body or "Live Relay" in body or len(body)) + + +print("\n=== public smoke ===", flush=True) +smoke("https://dy.nomadro.live") +smoke("https://dylive.nomadro.com") +print("ALL_DONE") diff --git a/scripts/_deploy_normal_overview_ui_dual.py b/scripts/_deploy_normal_overview_ui_dual.py new file mode 100644 index 0000000..520b2c9 --- /dev/null +++ b/scripts/_deploy_normal_overview_ui_dual.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Deploy normal-mode overview UI (YtAssignPanel) to dy then dylive. + +Build Next on dy (more RAM), copy .next tarball to dylive. Never recreate Neko. +""" +from __future__ import annotations + +import io +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +DY = "108.174.50.68" +DYLIVE = "107.173.30.245" + +FILES = [ + "frontend/src/components/YtAssignPanel.tsx", +] +MARKER = "普通频道 · 在播抖音" +TGZ = "/tmp/dy_next_normal_overview.tgz" + + +def connect(host: str, retries: int = 12): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail {host}: {last}") + + +def run(c, cmd: str, t: int = 1200) -> tuple[int, str]: + print(f"\n===== {cmd[:120].replace(chr(10), ' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +def put_text(sftp, local: Path, remote: str) -> None: + raw = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(raw) + + +for rel in FILES: + assert (ROOT / rel).is_file(), rel + +# ---------- dy ---------- +print("=== DY deploy ===", flush=True) +dy = connect(DY) +run( + dy, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; free -h | head -2", +) +sftp = dy.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +sftp.close() + +code, _ = run( + dy, + rf""" +set -euo pipefail +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +grep -n '{MARKER}' /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx | head -3 +cd /opt/douyinWEB/frontend +NODE_OPTIONS='--max-old-space-size=1536' npm run build +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +rm -f {TGZ} +tar -C /opt/douyinWEB/frontend -czf {TGZ} .next +ls -lh {TGZ} +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | head -c 120; echo +curl -sS -m 15 -b "$CS" -o /dev/null -w 'youtube:%{{http_code}}\n' http://127.0.0.1:4015/youtube +grep -Rnl '{MARKER}' /opt/douyinWEB/frontend/.next/static 2>/dev/null | head -3 || true +docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort +echo DY_DONE +""", + t=1800, +) +if code != 0: + dy.close() + raise SystemExit(f"dy deploy failed: {code}") + +print("=== transfer .next to local buffer ===", flush=True) +sftp = dy.open_sftp() +buf = io.BytesIO() +sftp.getfo(TGZ, buf) +sftp.close() +dy.close() +print(f"tarball bytes={buf.tell()}", flush=True) + +# ---------- dylive ---------- +print("=== DYLIVE deploy ===", flush=True) +dl = connect(DYLIVE) +run( + dl, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; free -h | head -2", +) +sftp = dl.open_sftp() +for rel in FILES: + put_text(sftp, ROOT / rel, f"/tmp/{Path(rel).name}") +buf.seek(0) +with sftp.file(TGZ, "wb") as f: + f.write(buf.getvalue()) +sftp.close() + +code, _ = run( + dl, + rf""" +set -euo pipefail +BEFORE=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo BEFORE_NEKO=$BEFORE + +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +grep -n '{MARKER}' /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx | head -3 + +cd /opt/douyinWEB/frontend +rm -rf .next.bak-normal-overview +if [ -d .next ]; then mv .next .next.bak-normal-overview; fi +tar -xzf {TGZ} +test -d .next +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web + +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | head -c 120; echo +curl -sS -m 15 -b "$CS" -o /dev/null -w 'youtube:%{{http_code}}\n' http://127.0.0.1:4015/youtube +grep -Rnl '{MARKER}' /opt/douyinWEB/frontend/.next/static 2>/dev/null | head -3 || true + +AFTER=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo AFTER_NEKO=$AFTER +docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort +free -h | head -2 +echo DYLIVE_DONE +""", + t=300, +) +dl.close() +if code != 0: + raise SystemExit(f"dylive deploy failed: {code}") + +CTX = ssl.create_default_context() + + +def smoke(base: str) -> None: + jar = CookieJar() + opener = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(jar), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with opener.open(req, timeout=25) as r: + print(base, "login", r.status, flush=True) + with opener.open(urllib.request.Request(f"{base}/youtube", method="GET"), timeout=25) as r: + body = r.read(200000).decode("utf-8", "replace") + hit = MARKER in body or "normalLiveRooms" in body + print(base, "youtube", r.status, "marker" if MARKER in body else ("chunk?" if hit else "no_marker_in_html"), flush=True) + + +print("=== public smoke ===", flush=True) +for url in ("https://dy.nomadro.live", "https://dylive.nomadro.com"): + try: + smoke(url) + except Exception as e: + print(url, "SMOKE_ERR", e, flush=True) + +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_ops_live_gate.py b/scripts/_deploy_ops_live_gate.py new file mode 100644 index 0000000..b79511a --- /dev/null +++ b/scripts/_deploy_ops_live_gate.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy remote ops-neko Live-page gate for auto-relay.""" +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/app/ops_neko_sync.py", +] + + +def put(c, root: str, sudo: str | None = None) -> None: + sftp = c.open_sftp() + for rel in FILES: + src = LOCAL / rel + tmp = f"/tmp/_ops_live_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(src.read_bytes()) + dst = f"{root}/{rel}".replace("\\", "/") + if sudo: + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc " + f"\"mkdir -p $(dirname {dst}); cat {tmp} > {dst}; sed -i 's/\\r$//' {dst}; chmod 644 {dst}\"" + ) + else: + cmd = f"mkdir -p $(dirname {dst}); cat {tmp} > {dst}; sed -i 's/\\r$//' {dst}; chmod 644 {dst}" + _i, o, e = c.exec_command(cmd, timeout=40) + err = (e.read() or b"").decode("utf-8", "replace") + print("ok", rel, err.strip()[:80], flush=True) + sftp.close() + + +def restart_api(c, sudo: str | None = None) -> None: + if sudo: + c.exec_command(f"echo {sudo} | sudo -S -p '' systemctl restart douyinweb-api", timeout=60)[1].read() + time.sleep(3) + _i, o, e = c.exec_command( + f"echo {sudo} | sudo -S -p '' systemctl is-active douyinweb-api; " + "grep -c wait_group_ready_for_live /opt/douyinWEB/backend/app/youtube_relay_pipeline.py; " + "grep -c ensure_slot_live_studio /opt/douyinWEB/backend/app/ops_neko.py", + timeout=30, + ) + else: + c.exec_command("systemctl restart douyinweb-api", timeout=60)[1].read() + time.sleep(3) + _i, o, e = c.exec_command( + "systemctl is-active douyinweb-api; " + "grep -c wait_group_ready_for_live /opt/douyinWEB/backend/app/youtube_relay_pipeline.py; " + "grep -c ensure_slot_live_studio /opt/douyinWEB/backend/app/ops_neko.py", + timeout=30, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def main() -> None: + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== PHYS ===", flush=True) + put(p, "/opt/douyinWEB", "4669805") + restart_api(p, "4669805") + # write ensure script then run + sftp = p.open_sftp() + with sftp.file("/tmp/_ensure_ops_live.py", "wb") as f: + f.write( + b"import sys\n" + b"sys.path.insert(0,'/opt/douyinWEB/backend')\n" + b"from app import ops_neko\n" + b"print(ops_neko.ensure_bound_slots_live_studio())\n" + ) + sftp.close() + _i, o, e = p.exec_command( + "echo 4669805 | sudo -S -p '' bash -lc '" + "cd /opt/douyinWEB/backend; " + "if [ -x .venv/bin/python ]; then .venv/bin/python /tmp/_ensure_ops_live.py; " + "else python3 /tmp/_ensure_ops_live.py; fi" + "'", + timeout=90, + ) + print("PHYS_ENSURE", (o.read() + e.read()).decode("utf-8", "replace"), flush=True) + p.close() + + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== VPS ===", flush=True) + put(v, "/opt/douyinWEB") + restart_api(v) + v.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_opsneko_pairing_ui.py b/scripts/_deploy_opsneko_pairing_ui.py new file mode 100644 index 0000000..2819bcc --- /dev/null +++ b/scripts/_deploy_opsneko_pairing_ui.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy ops-neko pairing UI/API to VPS + physical.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/ops_neko.py", + "backend/app/ops_neko_db.py", + "backend/app/main.py", + "backend/app/session_auth.py", + "frontend/src/components/OpsNekoHubCredentialsCard.tsx", + "frontend/src/components/YtRelayOpsHero.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/app/neko/page.tsx", +] + + +def put(c, root: str, sudo_pw: str | None = None): + sftp = c.open_sftp() + for rel in FILES: + src = LOCAL / rel + if not src.is_file(): + print("skip missing", rel) + continue + tmp = f"/tmp/_pair_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(src.read_bytes()) + dst = f"{root}/{rel}" + if sudo_pw: + cmd = f"echo '{sudo_pw}' | sudo -S -p '' bash -lc \"mkdir -p $(dirname {dst}); install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + else: + cmd = f"mkdir -p $(dirname {dst}); install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + _i, o, e = c.exec_command(cmd, timeout=30) + err = (e.read() + o.read()).decode("utf-8", "replace") + print(("ok " if not err.strip() or "password" in err.lower() else err[:120]), rel, flush=True) + sftp.close() + + +def main(): + # physical + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== PHYS ===", flush=True) + put(p, "/opt/douyinWEB", "4669805") + _i, o, e = p.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc '" + "systemctl restart douyinweb-api; " + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_pair.log 2>&1 && echo FE_OK || (echo FE_FAIL; tail -25 /tmp/fe_pair.log); " + "systemctl restart douyinweb-web; " + "systemctl is-active douyinweb-api douyinweb-web" + "'", + timeout=600, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + p.close() + + # vps + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== VPS ===", flush=True) + put(v, "/opt/douyinWEB") + _i, o, e = v.exec_command( + "systemctl restart douyinweb-api; " + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_pair.log 2>&1 && echo FE_OK || (echo FE_FAIL; tail -25 /tmp/fe_pair.log); " + "systemctl restart douyinweb-web; " + "sleep 2; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "curl -sS -m 12 -o /dev/null -w 'dy=%{http_code}\\n' https://dy.nomadro.com/api/health", + timeout=600, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + v.close() + print("DONE deploy pairing", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_opsneko_realtime.py b/scripts/_deploy_opsneko_realtime.py new file mode 100644 index 0000000..c6e5cf5 --- /dev/null +++ b/scripts/_deploy_opsneko_realtime.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy realtime ops-neko sync to physical + VPS.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/ops_neko_sync.py", + "backend/app/ops_neko.py", + "backend/app/main.py", + "frontend/src/app/neko/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/OpsNekoHubCredentialsCard.tsx", +] + + +def put(c, root, sudo_pw=None): + sftp = c.open_sftp() + for rel in FILES: + src = LOCAL / rel + tmp = f"/tmp/_rt_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(src.read_bytes()) + dst = f"{root}/{rel}" + if sudo_pw: + cmd = ( + f"echo '{sudo_pw}' | sudo -S -p '' bash -lc " + f"\"mkdir -p $(dirname {dst}); install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + ) + else: + cmd = f"mkdir -p $(dirname {dst}); install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + _i, o, e = c.exec_command(cmd, timeout=30) + (o.read() + e.read()) + print("ok", rel, flush=True) + sftp.close() + + +def main(): + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== PHYS ===", flush=True) + put(p, "/opt/douyinWEB", "4669805") + _i, o, e = p.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc '" + "systemctl restart douyinweb-api; " + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_rt.log 2>&1 && echo FE_OK || (tail -20 /tmp/fe_rt.log; echo FE_FAIL); " + "systemctl restart douyinweb-web; " + "sleep 2; systemctl is-active douyinweb-api; " + "curl -sS -m 8 -b /tmp/c -c /tmp/c -X POST http://127.0.0.1:8014/api/auth/login " + " -H \"Content-Type: application/json\" " + " -d \"{\\\"username\\\":\\\"hackrobot\\\",\\\"password\\\":\\\"Xiao4669805@\\\"}\" >/dev/null; " + "curl -sS -m 8 -b /tmp/c http://127.0.0.1:8014/api/ops/neko/sync-status" + "'", + timeout=600, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + p.close() + + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("=== VPS ===", flush=True) + put(v, "/opt/douyinWEB") + _i, o, e = v.exec_command( + "systemctl restart douyinweb-api; " + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_rt.log 2>&1 && echo FE_OK || (tail -20 /tmp/fe_rt.log; echo FE_FAIL); " + "systemctl restart douyinweb-web; " + "sleep 2; curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health", + timeout=600, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + v.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_p0_telemetry_gate.py b/scripts/_deploy_p0_telemetry_gate.py new file mode 100644 index 0000000..4da92db --- /dev/null +++ b/scripts/_deploy_p0_telemetry_gate.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy P0 telemetry/gate fixes — in-place overwrite, restart API only.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/main.py", + "backend/neko/live-ops-extension/background.js", + "backend/neko/live-ops-extension/content.js", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/neko/cdp_studio_scrape.py", +] + + +def deploy(host: str, port: int, user: str, pw: str, sudo: bool) -> None: + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + sftp = c.open_sftp() + pairs = [] + for rel in FILES: + local = ROOT / rel + tmp = f"/tmp/_p0_{rel.replace('/', '_')}" + with sftp.file(tmp, "wb") as f: + f.write(local.read_bytes()) + pairs.append((tmp, f"/opt/douyinWEB/{rel}")) + print("upload", rel) + sh = ["#!/bin/bash", "set -e"] + for tmp, dst in pairs: + sh.append(f"mkdir -p \"$(dirname '{dst}')\"") + sh.append(f"cp -a '{dst}' \"{dst}.bak.p0_$(date +%Y%m%d_%H%M%S)\" 2>/dev/null || true") + sh.append(f"cat '{tmp}' > '{dst}'") + sh.append(f"echo updated {dst}") + sh.append("systemctl restart douyinweb-api || systemctl restart douyinweb || true") + sh.append("sleep 3") + sh.append("systemctl is-active douyinweb-api || systemctl is-active douyinweb || true") + sh.append("curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 120; echo") + # sanity: mirror helper present + sh.append("grep -n 'Never invent' /opt/douyinWEB/backend/app/youtube_neko.py | head -2") + sh.append("grep -n 'dylive.nomadro.com' /opt/douyinWEB/backend/neko/live-ops-extension/background.js | head -2") + with sftp.file("/tmp/_deploy_p0_telemetry.sh", "w") as f: + f.write("\n".join(sh) + "\n") + sftp.close() + cmd = ( + f"echo '{pw}' | sudo -S -p '' bash /tmp/_deploy_p0_telemetry.sh" + if sudo + else "bash /tmp/_deploy_p0_telemetry.sh" + ) + _i, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def main() -> None: + deploy("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("\nDone. No Chrome restart (login safe). Extension picks dylive on next SW/content cycle.") + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_prefer_non_uhd_dual.py b/scripts/_deploy_prefer_non_uhd_dual.py new file mode 100644 index 0000000..c75b8d6 --- /dev/null +++ b/scripts/_deploy_prefer_non_uhd_dual.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Deploy latest project sources to BOTH VPS (dy + dylive): backend critical + FE rebuild sync.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805" + +# Full set of files that must match local workspace on both hosts. +SYNC_FILES = [ + "backend/app/douyin.py", + "backend/app/session_auth.py", + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/youtube_relay_status.py", + "backend/app/pb_sync.py", + "backend/app/main.py", + "backend/app/yt_assign_db.py", + "backend/tests/test_prefer_non_uhd_stream.py", + "frontend/src/lib/api.js", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/components/OpsNekoHubCredentialsCard.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "README.md", +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, script: str, timeout: int = 900) -> str: + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put_file(c, local: Path, remote: str): + sftp = c.open_sftp() + # ensure parent + remote_dir = "/".join(remote.split("/")[:-1]) + run(c, f"mkdir -p {remote_dir}", timeout=30) + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + sftp.close() + + +def sha12(p: Path) -> str: + return hashlib.sha256(p.read_bytes()).hexdigest()[:12] + + +print("LOCAL hashes:", flush=True) +for rel in SYNC_FILES: + p = ROOT / rel.replace("/", "\\") + if not p.exists(): + print("MISSING_LOCAL", rel, flush=True) + continue + print(f" {sha12(p)} {rel}", flush=True) + +# --- DY first: upload + pytest + API restart + FE build --- +print("\n######## DEPLOY dy 108.174.50.68 ########", flush=True) +c = connect(DY) +for rel in SYNC_FILES: + p = ROOT / rel.replace("/", "\\") + if not p.exists(): + continue + put_file(c, p, f"/opt/douyinWEB/{rel}") + print("put", rel, flush=True) + +print( + run( + c, + r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.douyin import pick_stream_candidates +room={"stream_url":{"flv_pull_url":{ + "ORIGIN":"http://x/a_uhd.flv", + "HD1":"http://x/a_hd.flv", + "FULL_HD1":"http://x/a_fhd.flv", +}}} +c=pick_stream_candidates(room) +print('pick0', c[0]) +assert 'a_hd.flv' in c[0], c +assert '_uhd' in c[-1] or 'uhd' in c[-1] +print('non_uhd_ok') +PY +systemctl restart douyinweb-api +sleep 2 +systemctl is-active douyinweb-api +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build 2>&1 | tail -30 +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +tar -C /opt/douyinWEB/frontend -czf /tmp/next-dual-sync.tgz .next +tar -C /opt/douyinWEB -czf /tmp/src-dual-sync.tgz \ + backend/app/douyin.py \ + backend/app/session_auth.py \ + backend/app/youtube_neko.py \ + backend/app/youtube_relay_pipeline.py \ + backend/app/youtube_relay_status.py \ + backend/app/pb_sync.py \ + backend/app/main.py \ + backend/app/yt_assign_db.py \ + backend/tests/test_prefer_non_uhd_stream.py \ + frontend/src/lib/api.js \ + frontend/src/components/YtRelayProStatusPanel.tsx \ + frontend/src/components/OpsNekoHubCredentialsCard.tsx \ + frontend/src/components/YtAssignPanel.tsx \ + README.md +ls -lh /tmp/next-dual-sync.tgz /tmp/src-dual-sync.tgz +""", + timeout=900, + ), + flush=True, +) + +sftp = c.open_sftp() +sftp.get("/tmp/next-dual-sync.tgz", str(ROOT / "scripts/_next-dual-sync.tgz")) +sftp.get("/tmp/src-dual-sync.tgz", str(ROOT / "scripts/_src-dual-sync.tgz")) +sftp.close() +c.close() + +# --- DYLIVE: extract src + .next, restart --- +print("\n######## DEPLOY dylive 107.173.30.245 ########", flush=True) +c = connect(DYLIVE) +put_file(c, ROOT / "scripts/_src-dual-sync.tgz", "/tmp/src-dual-sync.tgz") +put_file(c, ROOT / "scripts/_next-dual-sync.tgz", "/tmp/next-dual-sync.tgz") +print( + run( + c, + r""" +set -e +tar -C /opt/douyinWEB -xzf /tmp/src-dual-sync.tgz +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.douyin import pick_stream_candidates +room={"stream_url":{"flv_pull_url":{"ORIGIN":"http://x/a_uhd.flv","HD1":"http://x/a_hd.flv"}}} +assert 'a_hd.flv' in pick_stream_candidates(room)[0] +print('inline_ok') +PY +systemctl restart douyinweb-api +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_dual +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_dual 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-dual-sync.tgz +systemctl start douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +python3 - <<'PY' +import hashlib, pathlib +for rel in [ + 'backend/app/douyin.py', + 'backend/app/session_auth.py', + 'backend/app/youtube_neko.py', + 'frontend/src/lib/api.js', + 'frontend/src/components/YtRelayProStatusPanel.tsx', +]: + p=pathlib.Path('/opt/douyinWEB')/rel + print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel) +PY +# show ladder comment present +grep -n 'Prefer non-UHD\|HD1 → FULL_HD1\|prefer \*\*non-UHD\*\*' /opt/douyinWEB/backend/app/douyin.py | head -5 +""", + timeout=180, + ), + flush=True, +) +c.close() + +# verify hashes match local +print("\n######## HASH VERIFY ########", flush=True) +local = {rel: sha12(ROOT / rel.replace("/", "\\")) for rel in SYNC_FILES if (ROOT / rel.replace("/", "\\")).exists()} +for label, host in [("dy", DY), ("dylive", DYLIVE)]: + c = connect(host) + out = run( + c, + "python3 - <<'PY'\n" + "import hashlib, pathlib\n" + "files=" + repr([r for r in SYNC_FILES if r.startswith('backend/') or r.startswith('frontend/')]) + "\n" + "root=pathlib.Path('/opt/douyinWEB')\n" + "for rel in files:\n" + " p=root/rel\n" + " print(hashlib.sha256(p.read_bytes()).hexdigest()[:12] if p.exists() else 'MISSING', rel)\n" + "PY", + timeout=60, + ) + print(label, flush=True) + mismatch = 0 + for line in out.splitlines(): + parts = line.strip().split(None, 1) + if len(parts) != 2: + continue + h, rel = parts + exp = local.get(rel) + ok = exp and h == exp + if exp and not ok: + mismatch += 1 + print(f" MISMATCH {rel} remote={h} local={exp}", flush=True) + else: + print(f" OK {h} {rel}", flush=True) + print(f" mismatches={mismatch}", flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_preparing_status_flap.py b/scripts/_deploy_preparing_status_flap.py new file mode 100644 index 0000000..fecb7c8 --- /dev/null +++ b/scripts/_deploy_preparing_status_flap.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Deploy Preparing-stream gate + orphan-ffmpeg status flap fix to dylive.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-18000:] if len(out) > 18000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +for rel, remote in [ + ("backend/neko/cdp_studio_scrape.py", "/tmp/cdp_studio_scrape.py"), + ("backend/app/youtube_neko.py", "/tmp/youtube_neko.py"), + ("backend/app/youtube_relay_pipeline.py", "/tmp/youtube_relay_pipeline.py"), + ("backend/tests/test_preparing_stream_gate.py", "/tmp/test_preparing_stream_gate.py"), +]: + sftp.put(str(ROOT / rel), remote) +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail +install -m 0644 /tmp/cdp_studio_scrape.py /opt/douyinWEB/backend/neko/cdp_studio_scrape.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/test_preparing_stream_gate.py /opt/douyinWEB/backend/tests/test_preparing_stream_gate.py +cd /opt/douyinWEB/backend +./.venv/bin/python -m py_compile app/youtube_neko.py app/youtube_relay_pipeline.py neko/cdp_studio_scrape.py +./.venv/bin/python -m pytest -q tests/test_preparing_stream_gate.py +systemctl restart douyinweb-api.service +sleep 4 +systemctl is-active douyinweb-api.service +""", +) +assert code == 0, "deploy failed" + +# Probe asian streetfood / status flap + studio scrape fields +code2, out2 = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, urllib.request +from app import db, yt_assign_db, youtube_relay_db +from app.youtube_relay_pipeline import youtube_relay_pipeline as pipe, _ffmpeg_pid_alive +from app import youtube_neko + +# Find asian streetfood cards +groups = yt_assign_db.list_groups(featured_only=False) +hits = [g for g in groups if "asian" in str(g.get("name") or "").lower()] +print("asian_groups", [(g.get("id"), g.get("name"), g.get("neko_instance_id"), g.get("category")) for g in hits]) +st = pipe.status() +rows = {str(r.get("group_id") or ""): r for r in (st.get("groups") or [])} +for g in hits: + gid = str(g.get("id") or "") + mon = rows.get(gid) or {} + dbst = youtube_relay_db.get_relay_state(gid) or {} + pid = int(dbst.get("ffmpeg_pid") or 0) + print(json.dumps({ + "gid": gid[:8], + "name": g.get("name"), + "biz": mon.get("business_status"), + "row_status": mon.get("status"), + "is_pushing": mon.get("is_pushing"), + "db_status": dbst.get("status"), + "ffmpeg_pid": pid, + "pid_alive": _ffmpeg_pid_alive(pid), + "session": gid in getattr(pipe, "_sessions", {}), + }, ensure_ascii=False)) + +# Live CDP scrape on neko-7 if present +nid = 7 +try: + sig = youtube_neko._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0) + print("cdp7", json.dumps({k: sig.get(k) for k in ( + "ok","live_status","on_air","preparing_stream","control_ready","health","encoder_receiving" + )}, ensure_ascii=False)) +except Exception as e: + print("cdp7_err", e) + +cfg = db.get_settings_map() +print("relay", cfg.get("youtube_relay_enabled"), "timeslot_test", cfg.get("youtube_relay_timeslot_test"), + "winner", str(cfg.get("youtube_relay_timeslot_test_group_id") or "")[:8]) +PY +""", +) +print("probe_exit", code2) +c.close() +print("DONE", time.strftime("%H:%M:%S")) diff --git a/scripts/_deploy_project_perf_dual.py b/scripts/_deploy_project_perf_dual.py new file mode 100644 index 0000000..7ad290c --- /dev/null +++ b/scripts/_deploy_project_perf_dual.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Deploy project-wide perf fixes to dy then dylive. Never recreate Neko.""" +from __future__ import annotations + +import io +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +DY, DYLIVE = "108.174.50.68", "107.173.30.245" +TGZ = "/tmp/dy_next_perf.tgz" + +FILES = [ + "backend/app/youtube_relay_pipeline.py", + "backend/app/pb_sync.py", + "backend/app/youtube_neko.py", + "backend/app/main.py", + "frontend/src/lib/api.js", + "frontend/src/lib/douyinLive.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/app/page.tsx", +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect(host, 22, "root", PASS, timeout=60, allow_agent=False, look_for_keys=False, banner_timeout=300) + return c + except Exception as e: + print(f"retry {host} {i}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, cmd: str, t: int = 1800) -> tuple[int, str]: + print(f"\n===== {cmd[:90].replace(chr(10),' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return code, out + + +def put(c, local: Path, remote_name: str) -> None: + raw = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp = c.open_sftp() + with sftp.file(f"/tmp/{remote_name}", "wb") as f: + f.write(raw) + sftp.close() + + +for rel in FILES: + assert (ROOT / rel).is_file(), rel + +print("=== DY ===", flush=True) +dy = connect(DY) +for rel in FILES: + put(dy, ROOT / rel, Path(rel).name) + +code, _ = run( + dy, + rf""" +set -euo pipefail +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/api.js /opt/douyinWEB/frontend/src/lib/api.js +install -m 0644 /tmp/douyinLive.ts /opt/douyinWEB/frontend/src/lib/douyinLive.ts +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/page.tsx /opt/douyinWEB/frontend/src/app/page.tsx +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import pb_sync, youtube_relay_pipeline +assert pb_sync._PB_TIMEOUT_SEC == 6.0 +assert youtube_relay_pipeline.YoutubeRelayPipeline()._STATUS_CACHE_TTL_SEC == 5.0 +print('backend_ok') +PY +# revive API if D-state +systemctl restart douyinweb-api +sleep 4 +curl -sS -m 10 -o /dev/null -w 'health:%{{http_code}}\n' http://127.0.0.1:8014/api/health +cd /opt/douyinWEB/frontend +NODE_OPTIONS='--max-old-space-size=1536' npm run build +systemctl restart douyinweb-web +sleep 2 +rm -f {TGZ} +tar -C /opt/douyinWEB/frontend -czf {TGZ} .next +ls -lh {TGZ} +curl -sS -m 10 -o /dev/null -w 'home:%{{http_code}}\n' http://127.0.0.1:4015/ +echo DY_DONE +""", +) +if code != 0: + dy.close() + raise SystemExit(f"dy fail {code}") + +sftp = dy.open_sftp() +buf = io.BytesIO() +sftp.getfo(TGZ, buf) +sftp.close() +dy.close() +print(f"tarball={buf.tell()}", flush=True) + +print("=== DYLIVE ===", flush=True) +dl = connect(DYLIVE) +for rel in FILES: + put(dl, ROOT / rel, Path(rel).name) +buf.seek(0) +sftp = dl.open_sftp() +with sftp.file(TGZ, "wb") as f: + f.write(buf.getvalue()) +sftp.close() + +code, _ = run( + dl, + rf""" +set -euo pipefail +BEFORE=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo BEFORE=$BEFORE +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/api.js /opt/douyinWEB/frontend/src/lib/api.js +install -m 0644 /tmp/douyinLive.ts /opt/douyinWEB/frontend/src/lib/douyinLive.ts +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/page.tsx /opt/douyinWEB/frontend/src/app/page.tsx +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import pb_sync; assert pb_sync._PB_TIMEOUT_SEC==6.0; print("ok")' +systemctl restart douyinweb-api +sleep 4 +curl -sS -m 10 -o /dev/null -w 'health:%{{http_code}}\n' http://127.0.0.1:8014/api/health +cd /opt/douyinWEB/frontend +rm -rf .next.bak-perf +[ -d .next ] && mv .next .next.bak-perf || true +tar -xzf {TGZ} +systemctl restart douyinweb-web +sleep 2 +curl -sS -m 10 -o /dev/null -w 'home:%{{http_code}}\n' http://127.0.0.1:4015/ +AFTER=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo AFTER=$AFTER +free -m | head -2 +echo DYLIVE_DONE +""", + t=300, +) +dl.close() +if code != 0: + raise SystemExit(f"dylive fail {code}") +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_project_perf_dual_finish.py b/scripts/_deploy_project_perf_dual_finish.py new file mode 100644 index 0000000..51a74fe --- /dev/null +++ b/scripts/_deploy_project_perf_dual_finish.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Finish perf deploy after API slow start; build FE; push dylive.""" +from __future__ import annotations + +import io +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +TGZ = "/tmp/dy_next_perf.tgz" + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect(host, 22, "root", PASS, timeout=60, allow_agent=False, look_for_keys=False, banner_timeout=300) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(3 + i) + raise SystemExit("ssh_fail") + + +def run(c, cmd: str, t: int = 1800) -> tuple[int, str]: + print(f"\n===== {cmd[:100].replace(chr(10),' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return code, out + + +print("=== DY finish ===", flush=True) +dy = connect("108.174.50.68") +code, _ = run( + dy, + rf""" +set +e +systemctl is-active douyinweb-api +journalctl -u douyinweb-api -n 40 --no-pager | tail -40 +# wait for listen +for i in $(seq 1 30); do + code=$(curl -sS -m 3 -o /dev/null -w '%{{http_code}}' http://127.0.0.1:8014/api/health 2>/dev/null || echo 000) + echo wait_$i=$code + if [ "$code" = "200" ]; then break; fi + if [ "$i" = "5" ]; then systemctl restart douyinweb-api; fi + sleep 2 +done +set -e +curl -sS -m 10 -o /dev/null -w 'health:%{{http_code}}\n' http://127.0.0.1:8014/api/health +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import pb_sync, youtube_relay_pipeline; print(pb_sync._PB_TIMEOUT_SEC, youtube_relay_pipeline.YoutubeRelayPipeline()._STATUS_CACHE_TTL_SEC)' +cd /opt/douyinWEB/frontend +NODE_OPTIONS='--max-old-space-size=1536' npm run build +systemctl restart douyinweb-web +sleep 2 +rm -f {TGZ} +tar -C /opt/douyinWEB/frontend -czf {TGZ} .next +ls -lh {TGZ} +curl -sS -m 10 -o /dev/null -w 'home:%{{http_code}}\n' http://127.0.0.1:4015/ +echo DY_DONE +""", +) +if code != 0: + dy.close() + raise SystemExit(f"dy fail {code}") + +sftp = dy.open_sftp() +buf = io.BytesIO() +sftp.getfo(TGZ, buf) +sftp.close() +dy.close() +print(f"tarball={buf.tell()}", flush=True) + +FILES = [ + "backend/app/youtube_relay_pipeline.py", + "backend/app/pb_sync.py", + "backend/app/youtube_neko.py", + "backend/app/main.py", + "frontend/src/lib/api.js", + "frontend/src/lib/douyinLive.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/app/page.tsx", +] + +print("=== DYLIVE ===", flush=True) +dl = connect("107.173.30.245") +sftp = dl.open_sftp() +for rel in FILES: + raw = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/{Path(rel).name}", "wb") as f: + f.write(raw) +buf.seek(0) +with sftp.file(TGZ, "wb") as f: + f.write(buf.getvalue()) +sftp.close() + +code, _ = run( + dl, + rf""" +set +e +BEFORE=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo BEFORE=$BEFORE +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/api.js /opt/douyinWEB/frontend/src/lib/api.js +install -m 0644 /tmp/douyinLive.ts /opt/douyinWEB/frontend/src/lib/douyinLive.ts +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +install -m 0644 /tmp/page.tsx /opt/douyinWEB/frontend/src/app/page.tsx +systemctl restart douyinweb-api +for i in $(seq 1 25); do + code=$(curl -sS -m 3 -o /dev/null -w '%{{http_code}}' http://127.0.0.1:8014/api/health 2>/dev/null || echo 000) + echo wait_$i=$code + [ "$code" = "200" ] && break + sleep 2 +done +cd /opt/douyinWEB/frontend +rm -rf .next.bak-perf +[ -d .next ] && mv .next .next.bak-perf || true +tar -xzf {TGZ} +systemctl restart douyinweb-web +sleep 2 +curl -sS -m 10 -o /dev/null -w 'home:%{{http_code}}\n' http://127.0.0.1:4015/ +AFTER=$(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}' | sort | tr '\n' ' ') +echo AFTER=$AFTER +free -m | head -2 +echo DYLIVE_DONE +""", + t=300, +) +dl.close() +if code != 0: + raise SystemExit(f"dylive fail {code}") +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_receiving_first_live.py b/scripts/_deploy_receiving_first_live.py new file mode 100644 index 0000000..164ccd0 --- /dev/null +++ b/scripts/_deploy_receiving_first_live.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy receiving-first live-map + probe youtube-svc on both hosts.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_live.py", + "backend/app/youtube_neko.py", +] + + +def deploy(host, port, user, pw, sudo: bool) -> None: + print(f"\n===== deploy {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + pairs = [] + for rel in FILES: + tmp = f"/tmp/_recv_{rel.replace('/', '_')}" + with sftp.file(tmp, "wb") as f: + f.write((ROOT / rel).read_bytes()) + pairs.append((tmp, f"/opt/douyinWEB/{rel}")) + sh = ["#!/bin/bash", "set -e"] + for tmp, dst in pairs: + sh.append(f"cat '{tmp}' > '{dst}'") + sh.append(f"echo updated {dst}") + sh.append("systemctl restart douyinweb-api || true") + sh.append("sleep 2") + sh.append("systemctl is-active douyinweb-api || true") + sh.append("curl -sS -m 4 -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health || true") + # youtube-svc probe + sh.append("systemctl is-active youtube-svc 2>/dev/null || systemctl is-active douyinweb-youtube-svc 2>/dev/null || echo 'no youtube-svc unit'") + sh.append("curl -sS -m 3 http://127.0.0.1:8099/health 2>/dev/null | head -c 120; echo") + sh.append("curl -sS -m 3 http://127.0.0.1:8089/health 2>/dev/null | head -c 120; echo") + with sftp.file("/tmp/_deploy_recv.sh", "w") as f: + f.write("\n".join(sh) + "\n") + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_deploy_recv.sh" if sudo else "bash /tmp/_deploy_recv.sh" + _, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def main() -> None: + deploy("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("107.173.30.245", 4014, "eric", "4669805", sudo=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_receiving_first_live2.py b/scripts/_deploy_receiving_first_live2.py new file mode 100644 index 0000000..773c061 --- /dev/null +++ b/scripts/_deploy_receiving_first_live2.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = ["backend/app/youtube_live.py", "backend/app/youtube_neko.py"] + + +def run(c, cmd, t=60): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def upload_and_apply(host, port, user, pw, sudo=False): + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_rf_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((ROOT / rel).read_bytes()) + dst = f"/opt/douyinWEB/{rel}" + if sudo: + print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat {tmp} > {dst}\"", 30).strip()) + else: + print(run(c, f"cat {tmp} > {dst} && echo OK {dst}", 20).strip()) + sftp.close() + # restart non-blocking then poll + if sudo: + run(c, f"echo '{pw}' | sudo -S -p '' systemctl restart douyinweb-api", 45) + else: + # fire and forget + run(c, "systemctl restart douyinweb-api >/tmp/_api_restart.log 2>&1 &", 10) + for i in range(15): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x", 10).strip() + a = run(c, "systemctl is-active douyinweb-api", 10).strip() + print(f" try{i} active={a} health={h}") + if h == "200": + break + print( + "marker", + run(c, "grep -c studio_receiving /opt/douyinWEB/backend/app/youtube_live.py", 10).strip(), + ) + print( + "yt-svc", + run( + c, + "systemctl is-active youtube-svc 2>/dev/null; curl -sS -m 2 http://127.0.0.1:8099/health 2>/dev/null | head -c 80; echo; ss -lntp | grep -E '8099|8089|9100' | head -5", + 15, + ).strip(), + ) + c.close() + + +def main(): + upload_and_apply("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + upload_and_apply("107.173.30.245", 4014, "eric", "4669805", sudo=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_receiving_first_panel_dual.py b/scripts/_deploy_receiving_first_panel_dual.py new file mode 100644 index 0000000..e52400c --- /dev/null +++ b/scripts/_deploy_receiving_first_panel_dual.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Deploy receiving-first Neko panel fix + douyin non-UHD to both VPS.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +DY, DYLIVE = "108.174.50.68", "107.173.30.245" +FILES = [ + "backend/app/douyin.py", + "frontend/src/components/YtRelayProStatusPanel.tsx", +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect(host, 22, "root", PASS, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, cmd, timeout=900): + _i, o, e = c.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put(c, local: Path, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + sftp.close() + + +for rel in FILES: + p = ROOT / rel.replace("/", "\\") + print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel, flush=True) + +print("=== dy upload+build ===", flush=True) +c = connect(DY) +for rel in FILES: + put(c, ROOT / rel.replace("/", "\\"), f"/opt/douyinWEB/{rel}") +print( + run( + c, + r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.douyin import pick_stream_candidates +room={"stream_url":{"flv_pull_url":{"ORIGIN":"http://x/a_uhd.flv","HD1":"http://x/a_hd.flv"}}} +assert 'a_hd.flv' in pick_stream_candidates(room)[0] +print('non_uhd_ok') +PY +grep -n 'YouTube 接流中\|推流接流\|receiving-first' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -10 +systemctl restart douyinweb-api +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build 2>&1 | tail -15 +systemctl restart douyinweb-web +tar -C /opt/douyinWEB/frontend -czf /tmp/next-recv-fix.tgz .next +tar -C /opt/douyinWEB -czf /tmp/src-recv-fix.tgz \ + backend/app/douyin.py \ + frontend/src/components/YtRelayProStatusPanel.tsx +ls -lh /tmp/next-recv-fix.tgz /tmp/src-recv-fix.tgz +systemctl is-active douyinweb-api douyinweb-web +""", + timeout=800, + ), + flush=True, +) +sftp = c.open_sftp() +sftp.get("/tmp/next-recv-fix.tgz", str(ROOT / "scripts/_next-recv-fix.tgz")) +sftp.get("/tmp/src-recv-fix.tgz", str(ROOT / "scripts/_src-recv-fix.tgz")) +sftp.close() +c.close() + +print("=== dylive sync ===", flush=True) +c = connect(DYLIVE) +put(c, ROOT / "scripts/_src-recv-fix.tgz", "/tmp/src-recv-fix.tgz") +put(c, ROOT / "scripts/_next-recv-fix.tgz", "/tmp/next-recv-fix.tgz") +print( + run( + c, + r""" +set -e +tar -C /opt/douyinWEB -xzf /tmp/src-recv-fix.tgz +systemctl restart douyinweb-api +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_recv +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_recv 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-recv-fix.tgz +systemctl start douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +python3 - <<'PY' +import hashlib, pathlib +for rel in ['backend/app/douyin.py','frontend/src/components/YtRelayProStatusPanel.tsx']: + p=pathlib.Path('/opt/douyinWEB')/rel + print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel) +PY +grep -n 'YouTube 接流中\|推流接流' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -5 +""", + timeout=120, + ), + flush=True, +) +c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_safe_multi_heal.py b/scripts/_deploy_safe_multi_heal.py new file mode 100644 index 0000000..4735f07 --- /dev/null +++ b/scripts/_deploy_safe_multi_heal.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy multi-area safe heal: neko OOM, orphan ffmpeg, yt-long pending, shorts disk, FE.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] +FILES = [ + ("backend/app/youtube_neko.py", "/opt/douyinWEB/backend/app/youtube_neko.py"), + ("backend/app/youtube_relay_pipeline.py", "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py"), + ("backend/app/yt_long_db.py", "/opt/douyinWEB/backend/app/yt_long_db.py"), + ("backend/app/shorts_pipeline.py", "/opt/douyinWEB/backend/app/shorts_pipeline.py"), + ("frontend/src/components/YtRelayProStatusPanel.tsx", "/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx"), + ("frontend/src/app/yt-long/page.tsx", "/opt/douyinWEB/frontend/src/app/yt-long/page.tsx"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +cd /opt/douyinWEB/backend +.venv/bin/python - <<'PY' +from app.youtube_neko import heal_crashed_assign_nekos, _container_state +from app.yt_long_db import list_pending_yt_long_jobs +print("heal_fn", heal_crashed_assign_nekos) +print("pending_sample", len(list_pending_yt_long_jobs(limit=5))) +st=_container_state(8, check_http=False) if True else {} +print("state_keys_ok", "oom_killed" in {"oom_killed":1}) +print("import_ok") +PY +systemctl restart douyinweb-api +for i in $(seq 1 20); do + code=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo "health $i $code" + [ "$code" = "200" ] && break + sleep 2 +done +cd /opt/douyinWEB/frontend +npm run build 2>&1 | tail -25 +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + for rel, dst in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + tmp = f"/tmp/_safe_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + _, o, e = c.exec_command(f"cp -a {dst} {dst}.bak_safeheal 2>/dev/null; cat {tmp} > {dst} && echo OK {dst}", timeout=30) + print((o.read() + e.read()).decode()[:200], flush=True) + with sftp.file("/tmp/_deploy_safe_heal.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_safe_heal.sh", timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace")[-4500:], flush=True) + c.close() + + +def main(): + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_safe_perf_opt.py b/scripts/_deploy_safe_perf_opt.py new file mode 100644 index 0000000..3e8ff9a --- /dev/null +++ b/scripts/_deploy_safe_perf_opt.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +"""Deploy safe perf hardenings (no business/data) to phys + VPS.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + +BACKEND = [ + "backend/app/main.py", + "backend/app/shellcrash_hub.py", + "backend/app/network_hub.py", + "backend/app/youtube_live.py", + "backend/app/youtube_neko.py", + "backend/app/youtube_client.py", + "backend/app/pb_sync.py", +] +FRONTEND = [ + "frontend/src/app/ops/mobile/page.tsx", + "frontend/src/lib/douyinLive.ts", + "frontend/src/lib/youtubeLive.ts", + "frontend/src/components/YtAssignPanel.tsx", +] + +REMOTE_SH = r"""#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +mkdir -p "$ROOT/backend/app" "$ROOT/frontend/src/app/ops/mobile" \ + "$ROOT/frontend/src/lib" "$ROOT/frontend/src/components" + +# Install uploaded files (LF-safe) +python3 - <<'PY' +from pathlib import Path +import os +pairs = [] +for name in os.listdir('/tmp'): + if not name.startswith('_dy_opt_'): + continue + # _dy_opt_N__relpath_with_underscores stored as map file +print('skip map') +PY + +i=0 +while [ -f "/tmp/_dy_opt_${i}.path" ]; do + rel=$(cat "/tmp/_dy_opt_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_opt_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\\r\\n',b'\\n').replace(b'\\r',b'\\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service + +# Rebuild frontend if sources changed (Next) +if [ -d "$ROOT/frontend" ] && command -v npm >/dev/null 2>&1; then + cd "$ROOT/frontend" + npm run build >/tmp/dy_opt_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -30 /tmp/dy_opt_fe.log; } + systemctl restart douyinweb-web.service 2>/dev/null || systemctl restart douyinweb-next.service 2>/dev/null || true + sleep 3 + systemctl is-active douyinweb-web.service 2>/dev/null || systemctl is-active douyinweb-next.service 2>/dev/null || true +fi + +# Verify markers in code +grep -n '_HEALTH_DEPS_CACHE\|deps_cached\|DY_LIVE_HTTP_PROBE\|include_minute_reports\|STATUS_CACHE_TTL' \ + "$ROOT/backend/app/main.py" "$ROOT/backend/app/shellcrash_hub.py" "$ROOT/backend/app/youtube_live.py" \ + "$ROOT/backend/app/youtube_neko.py" 2>/dev/null | head -25 + +curl -sS -m 5 http://127.0.0.1:8014/api/ping || true +echo +curl -sS -m 8 http://127.0.0.1:8014/api/health | python3 -c "import sys,json; d=json.load(sys.stdin); print('health ok',d.get('ok'),'deps_cached',d.get('deps_cached'),'yt', (d.get('youtube') or {}).get('ok'),'pb',(d.get('pocketbase') or {}).get('ok'),'s3',(d.get('s3') or {}).get('ok'))" || echo health_fail + +# second health should often be cached +sleep 1 +curl -sS -m 8 http://127.0.0.1:8014/api/health | python3 -c "import sys,json; d=json.load(sys.stdin); print('health2 deps_cached',d.get('deps_cached'))" || true + +systemctl is-active douyinweb-shellcrash-tuic-guard.service 2>/dev/null || true +systemctl is-active douyinweb-wireguard-watch.service douyinweb-neko-watch.service douyinweb-api-watch.service 2>/dev/null || true +""" + + +def deploy(label: str, host: str, port: int, user: str, pw: str, *, sudo: bool) -> None: + print(f"\n===== deploy {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=50, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + files = BACKEND + FRONTEND + for i, rel in enumerate(files): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_opt_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_opt_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_opt_remote.sh", "w") as f: + f.write(REMOTE_SH.replace("\r\n", "\n")) + sftp.close() + + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_opt_remote.sh" if sudo else "bash /tmp/_dy_opt_remote.sh" + _, o, e = c.exec_command(cmd, timeout=600) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out) + c.close() + + +def pub(base: str) -> None: + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=35) + with op.open(urllib.request.Request(base + "/api/health"), timeout=20) as r: + h = json.loads(r.read().decode()) + with op.open(urllib.request.Request(base + "/api/rooms?limit=5"), timeout=30) as r: + rooms = json.loads(r.read().decode()) + with op.open(urllib.request.Request(base + "/api/network/shellcrash/status"), timeout=40) as r: + sc = json.loads(r.read().decode()) + shell = sc.get("shellcrash") or sc + print( + base, + "health=", h.get("ok"), + "deps_cached=", h.get("deps_cached"), + "rooms=", len(rooms.get("rooms") or []), + "sc_node=", shell.get("selected_node"), + "sc_default=", shell.get("default_node"), + "allow_vless=", shell.get("allow_vless_autopick"), + ) + except Exception as exc: + print(base, "ERR", exc) + + +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +time.sleep(3) +print("\n===== public =====") +for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + pub(b) +print("done") diff --git a/scripts/_deploy_shared_neko_studio_gate.py b/scripts/_deploy_shared_neko_studio_gate.py new file mode 100644 index 0000000..ec0b7bb --- /dev/null +++ b/scripts/_deploy_shared_neko_studio_gate.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy shared-Neko Studio attribution gate (false 「频道在播」 fix). Prefer dy; also dylive.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend" / "app" / "youtube_live.py" +DST = "/opt/douyinWEB/backend/app/youtube_live.py" +PASS = "Xiao4669805" +HOSTS = [ + ("dy", "108.174.50.68"), + ("dylive", "107.173.30.245"), +] + +VERIFY = r''' +import asyncio, os, sys, json +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".") +from app import youtube_live +youtube_live._CACHE["at"] = 0.0 +youtube_live._CACHE["payload"] = None +youtube_live._LAST_OAUTH_AT = 0.0 + +WATCH = { + "UCtVfMFdLTN4ap__8g7MFtVw": "nomad_vlog_space", + "UCO9wMc9tj9mD221Gu0rLBeA": "nomadvlog_timeslot", +} + +async def main(): + m = await youtube_live.build_live_map(force=True) + ents = m.get("entries") or {} + print("live_count", m.get("live_count")) + for k, v in sorted(ents.items()): + if not isinstance(v, dict) or not v.get("is_live"): + continue + if not (str(k).startswith("assign:") or str(k).startswith("channel:")): + continue + cid = str(v.get("channel_id") or "") + tag = WATCH.get(cid, "") + print( + "LIVE", + tag or "-", + k[:48], + "src=" + str(v.get("source") or ""), + "title=" + str(v.get("title") or "")[:40], + ) + # Explicit offline check for nomad vlog (space card) if present + for k, v in ents.items(): + if not isinstance(v, dict): + continue + if str(v.get("channel_id") or "") != "UCtVfMFdLTN4ap__8g7MFtVw": + continue + print( + "CHECK_nomad_vlog", + k[:56], + "is_live=" + str(bool(v.get("is_live"))), + "src=" + str(v.get("source") or ""), + ) + +asyncio.run(main()) +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=90, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, cmd: str, t: int = 120) -> str: + _, o, e = c.exec_command(cmd, timeout=t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + with sftp.file("/tmp/_youtube_live.py", "wb") as f: + f.write(LOCAL.read_bytes()) + with sftp.file("/tmp/_verify_shared_neko.py", "w") as f: + f.write(VERIFY) + sftp.close() + print(run(c, f"cp -a {DST} {DST}.bak_shared_neko && cat /tmp/_youtube_live.py > {DST} && echo PUT_OK", 30).strip(), flush=True) + print( + run( + c, + "cd /opt/douyinWEB/backend && .venv/bin/python -c " + "\"from app.youtube_live import _studio_snap_belongs_to_assign_group; print('import_ok', _studio_snap_belongs_to_assign_group)\"", + 40, + ).strip(), + flush=True, + ) + run(c, "systemctl restart douyinweb-api >/tmp/_api_restart.txt 2>&1 &", 15) + for i in range(18): + time.sleep(2) + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print(f" health try{i} {h}", flush=True) + if h == "200": + break + if i == 8: + run( + c, + "systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", + 40, + ) + print(run(c, "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_shared_neko.py", 240)[:3000], flush=True) + c.close() + + +def main(): + if not LOCAL.is_file(): + raise SystemExit(f"missing {LOCAL}") + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_shellcrash_tuic_guard.py b/scripts/_deploy_shellcrash_tuic_guard.py new file mode 100644 index 0000000..d359e10 --- /dev/null +++ b/scripts/_deploy_shellcrash_tuic_guard.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +"""Deploy TUIC-first shellcrash + VLESS soft-guard (upload remote.sh; no nested heredoc).""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +TUIC = "1d2da142-singbox_tuic5" + +REMOTE_SH = r"""#!/bin/bash +set -euo pipefail +TUIC='1d2da142-singbox_tuic5' +mkdir -p /opt/douyinWEB/scripts/linux /opt/douyinWEB/backend/app /etc/systemd/system/douyinweb-api.service.d + +install -m 644 /tmp/_dy_sc_hub.py /opt/douyinWEB/backend/app/shellcrash_hub.py +# Force LF: Windows SFTP can leave CRLF which makes bash exit 2 immediately. +python3 - <<'PY' +from pathlib import Path +src=Path('/tmp/_dy_sc_guard.py') +dst=Path('/opt/douyinWEB/scripts/linux/shellcrash_tuic_guard.py') +text=src.read_bytes().replace(b'\r\n', b'\n').replace(b'\r', b'\n') +dst.write_bytes(text) +dst.chmod(0o755) +print('wrote', dst, 'bytes', len(text)) +PY +install -m 644 /tmp/_dy_sc_guard.service /etc/systemd/system/douyinweb-shellcrash-tuic-guard.service + +cat >/etc/systemd/system/douyinweb-api.service.d/shellcrash-tuic.conf </dev/null; then + echo "scrub $f" + sed -i "s|Environment=DY_SHELLCRASH_DEFAULT_NODE=.*|Environment=DY_SHELLCRASH_DEFAULT_NODE=${TUIC}|g" "$f" || true + fi +done +shopt -u nullglob + +systemctl daemon-reload +systemctl reset-failed douyinweb-shellcrash-tuic-guard.service || true +systemctl enable --now douyinweb-shellcrash-tuic-guard.service +# Hub/env already live from prior deploy; avoid another API bounce unless module missing TUIC default. +need_api=0 +if ! grep -q 'singbox_tuic5' /opt/douyinWEB/backend/app/shellcrash_hub.py; then need_api=1; fi +if ! systemctl show douyinweb-api.service -p Environment --no-pager 2>/dev/null | grep -q 'DY_SHELLCRASH_DEFAULT_NODE=1d2da142-singbox_tuic5'; then need_api=1; fi +if [ "$need_api" = 1 ]; then + systemctl restart douyinweb-api.service + sleep 5 +fi +sleep 2 +echo "=== units ===" +systemctl is-active douyinweb-api.service douyinweb-shellcrash-tuic-guard.service || true +systemctl --no-pager -l status douyinweb-shellcrash-tuic-guard.service 2>/dev/null | sed -n '1,16p' || true +systemctl is-active douyinweb-wireguard-watch.service douyinweb-neko-watch.service douyinweb-api-watch.service 2>/dev/null || true + +echo "=== clash now ===" +python3 <<'PY' +import json, urllib.request, urllib.parse, os +ctrl='http://127.0.0.1:9999' +tuic='1d2da142-singbox_tuic5' +try: + with urllib.request.urlopen(ctrl+'/proxies', timeout=5) as r: + ps=json.load(r).get('proxies') or {} +except Exception as e: + print('clash_api', e) + ps={} +now=None +for g in ('🚀 节点选择','GLOBAL'): + now=(ps.get(g) or {}).get('now') + if now: + print('selected_before', g, now) + break +if now and 'vless' in now.lower(): + for g in ('🚀 节点选择','GLOBAL'): + if g != 'GLOBAL' and g not in ps: + continue + enc=urllib.parse.quote(g, safe='') + req=urllib.request.Request( + ctrl+'/proxies/'+enc, + data=json.dumps({'name': tuic}).encode(), + method='PUT', + headers={'Content-Type':'application/json'}, + ) + try: + urllib.request.urlopen(req, timeout=5) + print('reverted', g, '->', tuic) + except Exception as e: + print('revert_fail', g, e) +else: + print('keep', now) +PY + +echo "=== code defaults ===" +python3 <<'PY' +import importlib.util +spec=importlib.util.spec_from_file_location('sc','/opt/douyinWEB/backend/app/shellcrash_hub.py') +m=importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +print('DEFAULT_NODE', m.DEFAULT_NODE) +print('ALLOW_VLESS', m.ALLOW_VLESS_AUTOPICK) +print('family', m._node_family(m.DEFAULT_NODE)) +print('candidates0', m.CANDIDATE_NODES[0]) +PY + +echo "=== api env ===" +systemctl show douyinweb-api.service -p Environment --no-pager 2>/dev/null | tr ' ' '\n' | grep -E 'SHELLCRASH|VLESS|TUIC' || true + +echo "=== grep hub ===" +grep -nE 'DEFAULT_NODE|ALLOW_VLESS|never auto|TUIC only' /opt/douyinWEB/backend/app/shellcrash_hub.py | head -15 +""" + +GUARD_UNIT = """[Unit] +Description=douyinWEB ShellCrash TUIC guard (block VLESS autopick) +After=network.target + +[Service] +Type=simple +Environment=DY_SHELLCRASH_DEFAULT_NODE=1d2da142-singbox_tuic5 +Environment=DY_SHELLCRASH_ALLOW_VLESS= +Environment=DY_SHELLCRASH_GUARD_INTERVAL=60 +ExecStart=/usr/bin/python3 /opt/douyinWEB/scripts/linux/shellcrash_tuic_guard.py +Restart=always +RestartSec=15 + +[Install] +WantedBy=multi-user.target +""" + + +def deploy(label: str, host: str, port: int, user: str, pw: str, *, sudo: bool) -> None: + print(f"\n===== deploy {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + sftp.put(str(ROOT / "backend/app/shellcrash_hub.py"), "/tmp/_dy_sc_hub.py") + # Upload guard as bytes with LF only + guard = (ROOT / "scripts/linux/shellcrash_tuic_guard.py").read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file("/tmp/_dy_sc_guard.py", "wb") as f: + f.write(guard) + with sftp.file("/tmp/_dy_sc_guard.service", "w") as f: + f.write(GUARD_UNIT.replace("\r\n", "\n")) + remote = REMOTE_SH.replace("\r\n", "\n") + with sftp.file("/tmp/_dy_sc_remote.sh", "w") as f: + f.write(remote) + sftp.close() + + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_sc_remote.sh" + else: + cmd = "bash /tmp/_dy_sc_remote.sh" + _, o, e = c.exec_command(cmd, timeout=180) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out) + c.close() + + +def public_sc_status(base: str) -> None: + import http.cookiejar + import urllib.request + + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=35) + with op.open(urllib.request.Request(base + "/api/network/shellcrash/status"), timeout=45) as r: + d = json.loads(r.read().decode()) + sc = d.get("shellcrash") or d + print( + base, + "selected=", sc.get("selected_node"), + "family=", sc.get("selected_family"), + "default=", sc.get("default_node"), + "allow_vless=", sc.get("allow_vless_autopick"), + "running=", sc.get("running"), + ) + except Exception as exc: + print(base, "status_err", exc) + + +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +time.sleep(4) +print("\n===== public verify =====") +for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + public_sc_status(b) +print("done") diff --git a/scripts/_deploy_shorts_api_cooldown.py b/scripts/_deploy_shorts_api_cooldown.py new file mode 100644 index 0000000..b2c3d48 --- /dev/null +++ b/scripts/_deploy_shorts_api_cooldown.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts YouTube API cool-down (1h after 429, ntfy once) to phys+VPS.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/shorts_yt_quota.py", + "backend/app/shorts_pipeline.py", + "backend/app/db.py", + "backend/tests/test_shorts_yt_quota.py", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_cool_${i}.path" ]; do + rel=$(cat "/tmp/_dy_cool_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_cool_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +python3 <<'PY' || true +import sqlite3, json, time +from pathlib import Path +dbp = Path("/opt/douyinWEB/backend/data/monitor.db") +if not dbp.is_file(): + print("no_db") +else: + conn = sqlite3.connect(str(dbp)) + row = conn.execute("SELECT value FROM kv_settings WHERE key=?", ("shorts_yt_quota_cooldown_sec",)).fetchone() + if not row: + conn.execute( + "INSERT INTO kv_settings(key,value) VALUES(?,?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + ("shorts_yt_quota_cooldown_sec", "3600"), + ) + conn.commit() + print("inserted shorts_yt_quota_cooldown_sec=3600") + else: + print("shorts_yt_quota_cooldown_sec=", row[0]) + try: + now = time.time() + recent = conn.execute( + "SELECT COUNT(*) FROM shorts_jobs j " + "JOIN shorts_channels c ON c.id = j.channel_pk " + "WHERE UPPER(TRIM(COALESCE(c.oauth_profile_id,''))) = 'B' " + "AND j.error LIKE '%429%' AND j.updated_at > ?", + (now - 3600,), + ).fetchone()[0] + print("recent_B_429_jobs", recent) + if recent >= 1: + raw = conn.execute("SELECT value FROM kv_settings WHERE key=?", ("shorts_yt_quota_by_profile",)).fetchone() + qmap = {} + if raw and raw[0]: + try: + qmap = json.loads(raw[0]) + if not isinstance(qmap, dict): + qmap = {} + except Exception: + qmap = {} + entry = dict(qmap.get("B") or {}) + until = max(float(entry.get("blocked_until") or 0), now + 3600) + # Must set Pacific date or _sync_profile_entry clears blocked_until + from datetime import datetime, timezone, timedelta + pt = datetime.fromtimestamp(now, tz=timezone(timedelta(hours=-7))).strftime("%Y-%m-%d") + entry.update({ + "blocked_until": until, + "quota_ntfy_at": float(entry.get("quota_ntfy_at") or now), + "date": pt, + "count": int(entry.get("count") or 90), + }) + qmap["B"] = entry + payload = json.dumps(qmap, ensure_ascii=False) + conn.execute( + "INSERT INTO kv_settings(key,value) VALUES(?,?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + ("shorts_yt_quota_by_profile", payload), + ) + conn.commit() + print("armed_B_cooldown_until", until) + except Exception as e: + print("arm_err", e) + conn.close() +PY + +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service + +grep -nE 'mark_api_quota_cooldown|DEFAULT_API_COOLDOWN|blocked_profile_ids|冷静约' \ + "$ROOT/backend/app/shorts_yt_quota.py" "$ROOT/backend/app/shorts_pipeline.py" | head -25 + +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_cool_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_cool_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_cool_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_cool_remote.sh" if sudo else "bash /tmp/_dy_cool_remote.sh" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) + print( + base, + "blocked=", st.get("upload_quota_blocked"), + "until=", st.get("upload_quota_blocked_until"), + "profiles=", st.get("upload_quota_blocked_profiles"), + "cooldown_sec=", st.get("yt_quota_cooldown_sec"), + "by_profile=", [ + { + "id": p.get("id"), + "blocked": p.get("blocked"), + "until": p.get("blocked_until"), + "used": p.get("used"), + } + for p in (st.get("yt_quota_by_profile") or []) + if p.get("blocked") or p.get("id") in ("A", "B") + ], + ) + except Exception as exc: + print(base, "ERR", exc) + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("\n===== public =====") + pub("https://dylive.nomadro.com") + pub("https://dy.nomadro.com") + print("done") diff --git a/scripts/_deploy_shorts_cooldown_fe_ytlong.py b/scripts/_deploy_shorts_cooldown_fe_ytlong.py new file mode 100644 index 0000000..8da4988 --- /dev/null +++ b/scripts/_deploy_shorts_cooldown_fe_ytlong.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +"""Deploy yt-long cool-down skip + Shorts FE cool-down banner to phys+VPS.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/yt_long_db.py", + "backend/app/yt_long_pipeline.py", + "frontend/src/app/shorts/page.tsx", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_cool2_${i}.path" ]; do + rel=$(cat "/tmp/_dy_cool2_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_cool2_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service + +cd "$ROOT/frontend" +npm run build >/tmp/dy_cool2_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -40 /tmp/dy_cool2_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service + +grep -nE 'defer_profile_yt_long|blocked_profile_ids|upload_quota_blocked' \ + "$ROOT/backend/app/yt_long_pipeline.py" "$ROOT/backend/app/yt_long_db.py" \ + "$ROOT/frontend/src/app/shorts/page.tsx" | head -20 + +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_cool2_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_cool2_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_cool2_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_cool2_remote.sh" if sudo else "bash /tmp/_dy_cool2_remote.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) + print( + base, + "blocked=", st.get("upload_quota_blocked"), + "profiles=", st.get("upload_quota_blocked_profiles"), + "cooldown=", st.get("yt_quota_cooldown_sec"), + ) + except Exception as exc: + print(base, "ERR", exc) + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("\n===== public =====") + pub("https://dylive.nomadro.com") + pub("https://dy.nomadro.com") + print("done") diff --git a/scripts/_deploy_shorts_frontload_pace.py b/scripts/_deploy_shorts_frontload_pace.py new file mode 100644 index 0000000..00927d6 --- /dev/null +++ b/scripts/_deploy_shorts_frontload_pace.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts 20:00/90% front-load pacing + pull-forward parked slots.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("backend/app/shorts_schedule.py", "/tmp/_dy_shorts_schedule.py"), + ("backend/app/shorts_pipeline.py", "/tmp/_dy_shorts_pipeline.py"), + ("frontend/src/app/shorts/page.tsx", "/tmp/_dy_shorts_page.tsx"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_dy_shorts_schedule.py','/opt/douyinWEB/backend/app/shorts_schedule.py'), + ('/tmp/_dy_shorts_pipeline.py','/opt/douyinWEB/backend/app/shorts_pipeline.py'), + ('/tmp/_dy_shorts_page.tsx','/opt/douyinWEB/frontend/src/app/shorts/page.tsx'), +] +for s,d in pairs: + p=Path(s); dst=Path(d) + dst.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('ok', dst, dst.stat().st_size) +PY +python3 -m py_compile /opt/douyinWEB/backend/app/shorts_schedule.py /opt/douyinWEB/backend/app/shorts_pipeline.py && echo py_ok +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service +# Force pull-forward of parked upload_at +python3 - <<'PY' +import sys +sys.path.insert(0,'/opt/douyinWEB/backend') +from app.shorts_schedule import fleet_pace_plan, pull_forward_due_uploads +plan=fleet_pace_plan() +print('pace', {k:plan.get(k) for k in ('uploaded','front_target','need_front','behind','urgent','recommended_global_gap_sec','recommended_channel_gap_sec','recommended_per_hour','deadline_progress')}) +n=pull_forward_due_uploads() +print('pulled', n) +plan2=fleet_pace_plan() +print('pace_after', {k:plan2.get(k) for k in ('uploaded','front_target','behind','recommended_global_gap_sec')}) +# due count +import sqlite3, time, datetime +BJ=datetime.timezone(datetime.timedelta(hours=8)) +now=time.time() +day=datetime.datetime.now(BJ).strftime('%Y-%m-%d') +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +due=fut=0 +hours={} +for r in con.execute("SELECT upload_at FROM shorts_jobs WHERE push_date=? AND status IN ('scheduled','recorded') AND IFNULL(clip_path,'')!=''",(day,)): + ua=float(r[0] or 0) + if ua<=now+90: due+=1 + else: fut+=1 + if ua>0: + h=datetime.datetime.fromtimestamp(ua,BJ).hour + hours[h]=hours.get(h,0)+1 +print('due_now', due, 'future', fut, 'by_hour', dict(sorted(hours.items()))) +con.close() +PY +cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -20 +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service +curl -sS -m 8 http://127.0.0.1:8014/api/ping; echo +''' + + +def deploy(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_pace.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_pace.sh" if sudo else "bash /tmp/_dy_pace.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_deploy_shorts_offline_skip.py b/scripts/_deploy_shorts_offline_skip.py new file mode 100644 index 0000000..f49f702 --- /dev/null +++ b/scripts/_deploy_shorts_offline_skip.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts offline rebind/skip + stop retrying dead streams.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/db.py", + "backend/app/shorts_pipeline.py", +] + +HEAL = r''' +import time +from app import db +from app.shorts_pipeline import skip_or_rebind_offline_pending +from app.timeutil import push_date_from_ts + +day = push_date_from_ts(time.time()) +now = time.time() +conn = db._connect() +try: + cur = conn.execute( + """ + UPDATE shorts_jobs + SET status='skipped', + error=CASE + WHEN IFNULL(error,'')='' THEN '直播间已停播,已释放当日名额' + WHEN error LIKE '%已释放%' THEN error + ELSE error || '(已改为释放名额)' + END, + updated_at=?, + finished_at=CASE WHEN IFNULL(finished_at,0)=0 THEN ? ELSE finished_at END + WHERE push_date=? + AND status='failed' + AND ( + error LIKE '%无法获取直播流%' + OR error LIKE '%已停播%' + OR lower(error) LIKE '%probe 404%' + OR lower(error) LIKE '%server returned 404%' + ) + """, + (now, now, day), + ) + print("healed_failed_to_skipped", cur.rowcount, "day", day) + conn.commit() +finally: + conn.close() +r = skip_or_rebind_offline_pending(limit=80) +print("offline_pending", r) +print("stats", db.shorts_stats(day).get("by_status")) +''' + +REMOTE = r"""#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_off_${i}.path" ]; do + rel=$(cat "/tmp/_dy_off_${i}.path") + dst="$ROOT/$rel" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_off_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +cd "$ROOT/backend" +/opt/douyinWEB/backend/.venv/bin/python /tmp/_dy_off_heal.py +grep -nE 'skip_or_rebind_offline|_try_rebind_shorts|无法解析直播流' \ + "$ROOT/backend/app/shorts_pipeline.py" | head -15 +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +""" + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_off_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_off_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + for j in range(len(FILES), 8): + try: + sftp.remove(f"/tmp/_dy_off_{j}.path") + except Exception: + pass + with sftp.file("/tmp/_dy_off_heal.py", "w") as f: + f.write(HEAL.replace("\r\n", "\n")) + with sftp.file("/tmp/_dy_off_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_off_remote.sh" if sudo else "bash /tmp/_dy_off_remote.sh" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def check(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + op.open( + urllib.request.Request( + base + "/api/auth/login", + data=data, + method="POST", + headers={"Content-Type": "application/json"}, + ), + timeout=30, + ) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=60) as r: + st = json.loads(r.read().decode()) + print(base, "stats", (st.get("stats") or {}).get("by_status"), "live", st.get("douyin_live_count")) + + +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("\n===== public =====") +for b in ("https://dylive.nomadro.com", "https://dy.nomadro.com"): + try: + check(b) + except Exception as exc: + print(b, "ERR", exc) +print("done") diff --git a/scripts/_deploy_shorts_progress_uploaded.py b/scripts/_deploy_shorts_progress_uploaded.py new file mode 100644 index 0000000..cf1d088 --- /dev/null +++ b/scripts/_deploy_shorts_progress_uploaded.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts progress = uploaded-only (UI + board + fill min_met).""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/db.py", + "backend/app/shorts_schedule.py", + "backend/app/shorts_pipeline.py", + "frontend/src/app/shorts/page.tsx", +] + +REMOTE = r"""#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +# drop stale markers from older deploys +for j in $(seq 0 15); do + [ -f "/tmp/_dy_spu_${j}.path" ] || continue +done +i=0 +while [ -f "/tmp/_dy_spu_${i}.path" ]; do + rel=$(cat "/tmp/_dy_spu_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_spu_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service + +cd "$ROOT/backend" +PYBIN=$(systemctl show -p ExecStart --value douyinweb-api.service | awk '{print $1}') +if [ -x "$PYBIN" ]; then + PYTHONPATH=. "$PYBIN" - <<'PY' || true +from app.shorts_schedule import pull_forward_due_uploads +print("pull_forward", pull_forward_due_uploads()) +PY +else + echo "skip pull_forward, no PYBIN" +fi + +cd "$ROOT/frontend" +npm run build >/tmp/dy_spu_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -40 /tmp/dy_spu_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service + +grep -nE 'pull_forward_due_uploads|EMERGENCY_CHANNEL_GAP' \ + "$ROOT/backend/app/shorts_schedule.py" | head -15 +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +""" + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_spu_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_spu_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + # clear leftover path markers + for j in range(len(FILES), 12): + try: + sftp.remove(f"/tmp/_dy_spu_{j}.path") + except Exception: + pass + with sftp.file("/tmp/_dy_spu_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_spu_remote.sh" if sudo else "bash /tmp/_dy_spu_remote.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/schedule"), timeout=40) as r: + board = json.loads(r.read().decode()) + chans = board.get("channels") or [] + sample = [] + for c in chans[:8]: + if not c.get("enabled"): + continue + sample.append( + { + "name": c.get("name"), + "used": c.get("used"), + "uploaded": c.get("uploaded"), + "pending": c.get("pending"), + "scheduled": c.get("scheduled"), + "gap": c.get("gap"), + "max_met": c.get("max_met"), + } + ) + print(base, "day=", board.get("push_date"), "sample=", json.dumps(sample, ensure_ascii=False)) + except Exception as exc: + print(base, "ERR", exc) + + +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +time.sleep(4) +print("\n===== public =====") +for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + pub(b) +print("done") diff --git a/scripts/_deploy_shorts_quota_rules.py b/scripts/_deploy_shorts_quota_rules.py new file mode 100644 index 0000000..bd7e913 --- /dev/null +++ b/scripts/_deploy_shorts_quota_rules.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts quota rules (1 room→1 ch, ≥10min gap, Beijing min fill) to phys+VPS.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/db.py", + "backend/app/shorts_schedule.py", + "backend/app/shorts_pipeline.py", + "backend/tests/test_shorts_gap_rules.py", +] + +REMOTE = r"""#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_sq_${i}.path" ]; do + rel=$(cat "/tmp/_dy_sq_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_sq_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service + +# Apply gap settings (operator rule) without touching room/channel business rows. +python3 <<'PY' +import json, urllib.request +# Update via local settings API if possible — else direct sqlite +try: + import sqlite3 + from pathlib import Path + dbp = Path('/opt/douyinWEB/backend/data/monitor.db') + if dbp.is_file(): + conn = sqlite3.connect(str(dbp)) + conn.row_factory = sqlite3.Row + for k,v in [('shorts_channel_min_gap_sec','600'),('shorts_upload_min_gap_sec','600')]: + row = conn.execute('SELECT value FROM settings WHERE key=?', (k,)).fetchone() + if row: + conn.execute('UPDATE settings SET value=? WHERE key=?', (v,k)) + else: + try: + conn.execute('INSERT INTO settings(key,value) VALUES(?,?)', (k,v)) + except Exception: + pass + conn.commit() + # show shorts enabled + gaps + keys=('shorts_enabled','shorts_channel_min_gap_sec','shorts_upload_min_gap_sec','shorts_dedupe_room_day') + for k in keys: + r=conn.execute('SELECT value FROM settings WHERE key=?',(k,)).fetchone() + print('setting', k, r['value'] if r else None) + # today quota summary via python import if path works + conn.close() +except Exception as e: + print('settings_err', e) +PY + +grep -nE 'CHANNEL_GAP_FLOOR|daily_min first|shorts_channel_last_slot|CHANNEL_GAP_FLOOR_SEC' \ + "$ROOT/backend/app/shorts_schedule.py" "$ROOT/backend/app/shorts_pipeline.py" "$ROOT/backend/app/db.py" | head -20 + +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +""" + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_sq_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_sq_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_sq_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_sq_remote.sh" if sudo else "bash /tmp/_dy_sq_remote.sh" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + try: + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) + print( + base, + "enabled=", st.get("enabled"), + "channel_gap=", st.get("channel_min_gap_sec"), + "upload_gap=", st.get("upload_min_gap_sec"), + "min_unmet=", (st.get("board") or {}).get("min_unmet"), + "gap=", (st.get("board") or {}).get("total_gap"), + ) + except Exception as exc: + print(base, "ERR", exc) + + +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +time.sleep(3) +print("\n===== public =====") +for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + pub(b) +print("done") diff --git a/scripts/_deploy_shorts_room_offsets.py b/scripts/_deploy_shorts_room_offsets.py new file mode 100644 index 0000000..5eadf83 --- /dev/null +++ b/scripts/_deploy_shorts_room_offsets.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +"""Deploy Shorts multi-channel room offsets + heal empty clips; turn off global room dedupe.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("backend/app/db.py", "/tmp/_dy_db.py"), + ("backend/app/shorts_pipeline.py", "/tmp/_dy_sp.py"), + ("backend/app/clip_cascade.py", "/tmp/_dy_cc.py"), + ("backend/app/clip_retention.py", "/tmp/_dy_cr.py"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_dy_db.py','/opt/douyinWEB/backend/app/db.py'), + ('/tmp/_dy_sp.py','/opt/douyinWEB/backend/app/shorts_pipeline.py'), + ('/tmp/_dy_cc.py','/opt/douyinWEB/backend/app/clip_cascade.py'), + ('/tmp/_dy_cr.py','/opt/douyinWEB/backend/app/clip_retention.py'), +] +for s,d in pairs: + p=Path(s); dst=Path(d) + dst.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('ok', dst) +PY + +# Heal empty-clip scheduled jobs + force new dedupe setting +python3 <<'PY' +import sqlite3, datetime, time +BJ=datetime.timezone(datetime.timedelta(hours=8)) +day=datetime.datetime.now(BJ).strftime('%Y-%m-%d') +now=time.time() +conn=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +# migrate column +cols={r[1] for r in conn.execute('PRAGMA table_info(shorts_jobs)')} +if 'clip_offset_sec' not in cols: + conn.execute('ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0') + print('added clip_offset_sec') +# settings +for k,v in [('shorts_dedupe_room_day','false'),('shorts_channel_min_gap_sec','600'),('shorts_upload_min_gap_sec','600'),('shorts_max_concurrent','3')]: + row=conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone() + if row: + conn.execute('UPDATE kv_settings SET value=? WHERE key=?',(v,k)) + else: + conn.execute('INSERT INTO kv_settings(key,value) VALUES(?,?)',(k,v)) + print('kv',k,v) +# heal +cur=conn.execute(""" +UPDATE shorts_jobs SET status='pending', clip_path='', clip_seconds=0, upload_at=0, + error='成片路径为空,已重新排队录制', finished_at=0, updated_at=? +WHERE push_date=? AND status IN ('scheduled','recorded','uploading') + AND IFNULL(youtube_video_id,'')='' AND IFNULL(clip_path,'')='' +""",(now,day)) +print('healed_empty', cur.rowcount, 'day', day) +rows=conn.execute('SELECT status,COUNT(*) FROM shorts_jobs WHERE push_date=? GROUP BY status',(day,)).fetchall() +print('jobs', dict(rows)) +conn.commit(); conn.close() +PY + +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +grep -n 'clip_offset_sec\|dedupe_room_global\|next_shorts_room_clip_offset' /opt/douyinWEB/backend/app/db.py /opt/douyinWEB/backend/app/shorts_pipeline.py | head -20 +''' + + +def deploy(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_room_off.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_room_off.sh" if sudo else "bash /tmp/_dy_room_off.sh" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + +time.sleep(3) +base = "https://dylive.nomadro.com" +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + base + "/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + method="POST", + headers={"Content-Type": "application/json"}, +) +op.open(req, timeout=30) +# force settings via API too +req2 = urllib.request.Request( + base + "/api/settings", + data=json.dumps({"shorts_dedupe_room_day": False, "shorts_channel_min_gap_sec": 600, "shorts_max_concurrent": 3}).encode(), + method="PATCH", + headers={"Content-Type": "application/json"}, +) +with op.open(req2, timeout=40) as r: + print("settings patched", bool(r.read())) +req3 = urllib.request.Request(base + "/api/shorts/fill-quota", data=b"{}", method="POST", headers={"Content-Type": "application/json"}) +with op.open(req3, timeout=90) as r: + st = json.loads(r.read().decode()) +print( + "fill just=", st.get("just_quota_filled"), + "active_rec=", st.get("active_records"), + "active_up=", st.get("active_uploads"), + "gap=", st.get("quota_gap"), + "pending-ish board unmet=", (st.get("board") or {}).get("min_unmet"), +) +print("done") diff --git a/scripts/_deploy_sigill_autoheal.py b/scripts/_deploy_sigill_autoheal.py new file mode 100644 index 0000000..def6023 --- /dev/null +++ b/scripts/_deploy_sigill_autoheal.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy Chrome SIGILL/Aw Snap auto-heal + run heal NOW on dy (and dylive).""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] +FILES = [ + ("backend/app/youtube_neko.py", "/opt/douyinWEB/backend/app/youtube_neko.py"), + ("backend/neko/browser-launch.sh", "/opt/douyinWEB/backend/neko/browser-launch.sh"), + ("scripts/linux/neko_health_watch.sh", "/opt/douyinWEB/scripts/linux/neko_health_watch.sh"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +chmod +x /opt/douyinWEB/backend/neko/browser-launch.sh || true +install -m 755 /opt/douyinWEB/scripts/linux/neko_health_watch.sh /usr/local/bin/neko_health_watch.sh 2>/dev/null || true +# Ensure watch timer/service picks up new script if unit exists (no config rewrite). +systemctl restart douyinweb-neko-watch.service 2>/dev/null || systemctl restart neko-health-watch.service 2>/dev/null || true +cd /opt/douyinWEB/backend +.venv/bin/python - <<'PY' +from app.youtube_neko import ( + heal_neko_runtime, + _chrome_tab_crash_reason, + _chrome_renderer_probe, + _devtools_version_ok, + _restart_chrome_in_container, + _cdp_nudge_live_studio_tab, +) +import json, time +print("pre_probe8", _chrome_renderer_probe(8)) +print("pre_crash8", _chrome_tab_crash_reason(8)) +print("pre_cdp8", _devtools_version_ok(8)) +# If still wedged, force Chrome soft-restart NOW (do not wait for loop). +reason = _chrome_tab_crash_reason(8) or _chrome_renderer_probe(8) +if reason: + print("FORCE_RESTART8", reason) + print("restart", _restart_chrome_in_container(8)) + time.sleep(5) + print("nudge", _cdp_nudge_live_studio_tab(8)) +print("HEAL_NOW", json.dumps(heal_neko_runtime(), ensure_ascii=False)[:2000]) +time.sleep(3) +print("post_probe8", _chrome_renderer_probe(8)) +print("post_crash8", _chrome_tab_crash_reason(8)) +print("post_cdp8", _devtools_version_ok(8)) +PY +systemctl restart douyinweb-api +for i in $(seq 1 20); do + c=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health_$i=$c + [ "$c" = "200" ] && break + sleep 2 +done +.venv/bin/python - <<'PY' +from app.youtube_neko import heal_neko_runtime, _chrome_renderer_probe +import json +print("HEAL_AFTER_API", json.dumps(heal_neko_runtime(), ensure_ascii=False)[:1500]) +print("final_probe8", _chrome_renderer_probe(8)) +PY +systemctl is-active douyinweb-api +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + for rel, dst in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + tmp = f"/tmp/_sigill_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + _, o, e = c.exec_command(f"mkdir -p $(dirname {dst}); cat {tmp} > {dst} && echo OK {dst}", timeout=30) + print((o.read() + e.read()).decode()[:200], flush=True) + with sftp.file("/tmp/_deploy_sigill_autoheal.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_sigill_autoheal.sh", timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")[-6000:], flush=True) + c.close() + + +def main(): + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_source_attrib_fix.py b/scripts/_deploy_source_attrib_fix.py new file mode 100644 index 0000000..71f1342 --- /dev/null +++ b/scripts/_deploy_source_attrib_fix.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +"""API-only hotpatch: stronger Douyin room attribution for analytics.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = ["backend/app/yt_studio_db.py"] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_src3_${i}.path" ]; do + rel=$(cat "/tmp/_dy_src3_${i}.path") + dst="$ROOT/$rel" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_src3_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +op.open(urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST'), timeout=20) +gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=30).read().decode()).get('groups') or [] +for g in gs: + gid=str(g.get('id')); name=g.get('name') + an=json.loads(op.open(f'http://127.0.0.1:8014/api/youtube/assign/groups/{gid}/analytics?days=30', timeout=120).read().decode()) + ranks=[r for r in (an.get('source_rankings') or []) if r.get('measured')] + with_avg=[r for r in ranks if r.get('avg_viewers') is not None] + print(name, 'measured', len(ranks), 'with_avg', len(with_avg), 'sessions', (an.get('overview') or {}).get('session_count')) + if with_avg: + t=with_avg[0] + print(' top_avg', t.get('anchor_name'), 'avg', t.get('avg_viewers'), 'peak', t.get('peak_viewers'), 'cover', bool(t.get('cover_url')), 'tip', (t.get('planning_tip') or '')[:60]) +PY +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_src3_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_src3_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_src3_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_src3_remote.sh" if sudo else "bash /tmp/_dy_src3_remote.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("done") diff --git a/scripts/_deploy_source_channel_analytics.py b/scripts/_deploy_source_channel_analytics.py new file mode 100644 index 0000000..0eaa63f --- /dev/null +++ b/scripts/_deploy_source_channel_analytics.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +"""Deploy Douyin-source × YouTube-channel planning analytics.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/yt_studio_db.py", + "backend/app/main.py", + "frontend/src/app/youtube/analytics/[groupId]/page.tsx", + "frontend/src/app/youtube/analytics/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_src_${i}.path" ]; do + rel=$(cat "/tmp/_dy_src_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_src_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service + +cd "$ROOT/frontend" +npm run build >/tmp/dy_src_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -60 /tmp/dy_src_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service + +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +op.open(urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST'), timeout=20) +gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=30).read().decode()) +groups=gs.get('groups') or [] +print('groups', len(groups)) +if groups: + gid=str(groups[0].get('id')) + an=json.loads(op.open(f'http://127.0.0.1:8014/api/youtube/assign/groups/{gid}/analytics?days=30', timeout=90).read().decode()) + ranks=an.get('source_rankings') or [] + measured=[r for r in ranks if r.get('measured')] + print('channel', (an.get('group') or {}).get('name'), 'measured_sources', len(measured), 'slots', len(an.get('planning_slots') or [])) + if measured: + t=measured[0] + print('top_source', t.get('anchor_name'), t.get('room_id'), 'cover', bool(t.get('cover_url')), 'score', t.get('score'), 'best', (t.get('best_hours') or [{}])[0].get('label')) +fleet=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/analytics/sources?days=30', timeout=120).read().decode()) +print('fleet_ok', fleet.get('ok'), 'recs', len(fleet.get('recommendations') or []), 'rooms', len(fleet.get('rooms') or [])) +PY +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_src_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_src_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_src_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_src_remote.sh" if sudo else "bash /tmp/_dy_src_remote.sh" + _, o, e = c.exec_command(cmd, timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("done") diff --git a/scripts/_deploy_source_channel_analytics2.py b/scripts/_deploy_source_channel_analytics2.py new file mode 100644 index 0000000..d1beccd --- /dev/null +++ b/scripts/_deploy_source_channel_analytics2.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +"""Hotfix source×channel analytics (API + FE) after relay room backfill.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/yt_studio_db.py", + "backend/app/main.py", + "frontend/src/app/youtube/analytics/[groupId]/page.tsx", + "frontend/src/app/youtube/analytics/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +ROOT=/opt/douyinWEB +i=0 +while [ -f "/tmp/_dy_src2_${i}.path" ]; do + rel=$(cat "/tmp/_dy_src2_${i}.path") + dst="$ROOT/$rel" + mkdir -p "$(dirname "$dst")" + python3 -c "from pathlib import Path; p=Path('/tmp/_dy_src2_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)" + i=$((i+1)) +done + +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service + +cd "$ROOT/frontend" +npm run build >/tmp/dy_src2_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -60 /tmp/dy_src2_fe.log; exit 1; } +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service + +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +op.open(urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST'), timeout=20) +gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=30).read().decode()) +groups=gs.get('groups') or [] +print('groups', len(groups)) +best=None +for g in groups[:8]: + gid=str(g.get('id')) + an=json.loads(op.open(f'http://127.0.0.1:8014/api/youtube/assign/groups/{gid}/analytics?days=30', timeout=120).read().decode()) + ranks=[r for r in (an.get('source_rankings') or []) if r.get('measured')] + print('ch', g.get('name'), 'measured', len(ranks), 'slots', len(an.get('planning_slots') or []), 'sessions', (an.get('overview') or {}).get('session_count')) + if ranks and (best is None or ranks[0].get('score',0) > best[1]): + best=(g.get('name'), float(ranks[0].get('score') or 0), ranks[0]) +if best: + t=best[2] + print('BEST', best[0], t.get('anchor_name'), t.get('room_id'), 'cover', bool(t.get('cover_url')), 'score', t.get('score'), 'avg', t.get('avg_viewers'), 'hours', [(h.get('label'), h.get('peak_viewers')) for h in (t.get('best_hours') or [])[:2]]) +fleet=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/analytics/sources?days=30', timeout=300).read().decode()) +print('fleet_ok', fleet.get('ok'), 'recs', len(fleet.get('recommendations') or []), 'rooms', len(fleet.get('rooms') or [])) +if fleet.get('recommendations'): + r=fleet['recommendations'][0] + print('top_pair', r.get('anchor_name'), '->', r.get('channel_name'), 'score', r.get('score'), 'cover', bool(r.get('cover_url'))) +PY +''' + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for i, rel in enumerate(FILES): + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(f"/tmp/_dy_src2_{i}.bin", "wb") as f: + f.write(data) + with sftp.file(f"/tmp/_dy_src2_{i}.path", "w") as f: + f.write(rel.replace("\\", "/")) + with sftp.file("/tmp/_dy_src2_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_src2_remote.sh" if sudo else "bash /tmp/_dy_src2_remote.sh" + _, o, e = c.exec_command(cmd, timeout=900) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("done") diff --git a/scripts/_deploy_stream_key_registry_dual.py b/scripts/_deploy_stream_key_registry_dual.py new file mode 100644 index 0000000..3059ed0 --- /dev/null +++ b/scripts/_deploy_stream_key_registry_dual.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Deploy stream-key registry to dy + dylive. + +SAFETY: +- Copy only listed app/frontend files +- Restart douyinweb-api + douyinweb-web only +- NEVER docker stop/rm/recreate any neko* +- NEVER wipe profiles / monitor.db / assign tables +""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +HOSTS = [ + ("dy", "108.174.50.68", "https://dy.nomadro.live"), + ("dylive", "107.173.30.245", "https://dylive.nomadro.com"), +] +PASS = "Xiao4669805" + +FILES = [ + "backend/app/yt_stream_key_db.py", + "backend/app/models.py", + "backend/app/main.py", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", +] + + +def connect(host: str): + last = None + for i in range(8): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + last = e + print(f" ssh_retry {i} {host}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh fail {host}: {last}") + + +def run(c, cmd: str, t: int = 600) -> tuple[int, str]: + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + return code, out + + +def upload_files(c, label: str) -> None: + sftp = c.open_sftp() + for rel in FILES: + local = ROOT / rel + assert local.is_file(), local + remote = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" + # ensure dir + parts = remote.split("/")[:-1] + cur = "" + for p in parts: + if not p: + continue + cur += "/" + p + try: + sftp.stat(cur) + except OSError: + try: + sftp.mkdir(cur) + except OSError: + pass + print(f" put {rel} -> {remote}", flush=True) + sftp.put(str(local), remote) + sftp.close() + + +def deploy_one(label: str, host: str, public: str) -> None: + print(f"\n======== {label} {host} ========", flush=True) + c = connect(host) + + # snapshot neko before + code, before = run( + c, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web", + ) + print("BEFORE:\n" + before, flush=True) + + upload_files(c, label) + + # rebuild web + restart api ONLY — no neko touch + code, out = run( + c, + r""" +set -euo pipefail +# guard: refuse if any command would touch neko (sanity) +cd /opt/douyinWEB/backend +# syntax check new module +./.venv/bin/python -c 'from app import yt_stream_key_db, models; print("py_ok", yt_stream_key_db)' + +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api + +# frontend rebuild (Next) without docker +if [ -d /opt/douyinWEB/frontend ]; then + cd /opt/douyinWEB/frontend + if [ -f package.json ]; then + # prefer existing next build flow used on host + if systemctl list-unit-files | grep -q '^douyinweb-web'; then + # build then restart web + export NODE_ENV=production + if [ -d node_modules ]; then + npm run build + else + echo 'WARN no node_modules — skip build, restart web only' + fi + systemctl restart douyinweb-web + sleep 3 + systemctl is-active douyinweb-web + fi + fi +fi + +# seed registry from assign (safe: only new table) +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_stream_key_db +print(yt_stream_key_db.import_from_assign_groups(replace=False)) +print(yt_stream_key_db.list_entries(include_secret=False)) +PY + +curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 180; echo +curl -sS -m 10 -o /dev/null -w 'keys_api:%{http_code}\n' http://127.0.0.1:8014/api/youtube/stream-keys || true +""", + t=900, + ) + print(out[-8000:] if len(out) > 8000 else out, flush=True) + if code != 0: + print(f"WARN deploy cmd exit {code}", flush=True) + + code2, after = run( + c, + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " + "systemctl is-active douyinweb-api douyinweb-web; " + f"curl -sk -m 15 -o /dev/null -w 'pub_keys:%{{http_code}}\\n' {public}/youtube/keys; " + f"curl -sk -m 15 -o /dev/null -w 'pub_yt:%{{http_code}}\\n' {public}/youtube", + ) + print("AFTER:\n" + after, flush=True) + + # assert same neko names still running (set compare of Up lines) + before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln} + after_up = {ln.split()[0] for ln in after.splitlines() if " Up " in ln and "neko" in ln} + lost = before_up - after_up + if lost: + print(f"CRITICAL neko lost on {label}: {lost}", flush=True) + raise SystemExit(2) + print(f"neko_ok {label} still_up={sorted(after_up)}", flush=True) + c.close() + + +def sync_registry_dy_to_dylive() -> None: + """Copy key registry secrets dy → dylive (table only).""" + print("\n======== sync registry dy → dylive ========", flush=True) + dy = connect("108.174.50.68") + code, out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +print('EXPORT_JSON_START') +print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False)) +print('EXPORT_JSON_END') +PY +""", + ) + dy.close() + start = out.find("EXPORT_JSON_START") + end = out.find("EXPORT_JSON_END") + if start < 0 or end < 0: + print("no export", out[-2000:]) + return + payload = json.loads(out[start + len("EXPORT_JSON_START") : end].strip()) + items = payload.get("items") or [] + print(f"export items={len(items)}", flush=True) + + dl = connect("107.173.30.245") + sftp = dl.open_sftp() + with sftp.file("/tmp/yt_stream_keys_import.json", "w") as f: + f.write(json.dumps({"items": items, "replace": False}, ensure_ascii=False)) + sftp.close() + code2, out2 = run( + dl, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +data=json.load(open('/tmp/yt_stream_keys_import.json',encoding='utf-8')) +print(yt_stream_key_db.import_payload(data.get('items') or [], replace=False)) +print('total', yt_stream_key_db.list_entries()['total']) +PY +# ensure neko untouched +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +""", + ) + print(out2, flush=True) + dl.close() + + +def main() -> None: + for rel in FILES: + assert (ROOT / rel).is_file(), rel + # dy first (where user added keys), then dylive + for label, host, public in HOSTS: + deploy_one(label, host, public) + sync_registry_dy_to_dylive() + print("\nALL_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_stream_key_registry_finish.py b/scripts/_deploy_stream_key_registry_finish.py new file mode 100644 index 0000000..092701f --- /dev/null +++ b/scripts/_deploy_stream_key_registry_finish.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Finish dual deploy: ensure dy Next build has /youtube/keys; deploy dylive when SSH works.""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +FILES = [ + "backend/app/yt_stream_key_db.py", + "backend/app/models.py", + "backend/app/main.py", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", +] + + +def connect(host: str): + last = None + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=240, + auth_timeout=60, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {i} {host}: {e}", flush=True) + time.sleep(4 + i * 2) + raise SystemExit(f"ssh fail {host}: {last}") + + +def run(c, cmd: str, t: int = 900) -> tuple[int, str]: + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + return o.channel.recv_exit_status(), out + + +def upload(c): + sftp = c.open_sftp() + for rel in FILES: + local = ROOT / rel + remote = f"/opt/douyinWEB/{rel}" + # mkdir -p + d = "/".join(remote.split("/")[:-1]) + run(c, f"mkdir -p {d}") + print("put", rel, flush=True) + sftp.put(str(local), remote) + sftp.close() + + +def ensure_frontend_build(c, label: str) -> None: + code, out = run( + c, + r""" +set -euo pipefail +echo '=== neko before ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +cd /opt/douyinWEB/frontend +ls -la page.tsx 2>/dev/null || true +test -f src/app/youtube/keys/page.tsx && echo keys_page_src_ok +# Does production build already include keys route? +if [ -d .next/server/app/youtube/keys ] || [ -f .next/server/app/youtube/keys/page.js ]; then + echo next_keys_built_already +else + echo need_build + if [ -d node_modules ]; then + # low-mem friendly + export NODE_OPTIONS=--max-old-space-size=1536 + npm run build + else + echo 'FATAL no node_modules' + exit 3 + fi +fi +systemctl restart douyinweb-web +sleep 4 +systemctl is-active douyinweb-web +echo '=== neko after ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +""", + t=900, + ) + print(out[-6000:] if len(out) > 6000 else out, flush=True) + if code != 0: + raise SystemExit(f"{label} frontend build failed: {code}") + + +print("===== dy frontend ensure =====", flush=True) +dy = connect("108.174.50.68") +ensure_frontend_build(dy, "dy") +# verify API still has keys +_, out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_stream_key_db +print('total', yt_stream_key_db.list_entries()['total']) +PY +curl -sk -m 15 -o /dev/null -w 'keys:%{http_code}\n' https://dy.nomadro.live/youtube/keys +""", +) +print(out, flush=True) +# export for dylive +_, exp = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +print('EXPORT_JSON_START') +print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False)) +print('EXPORT_JSON_END') +PY +""", +) +dy.close() +start = exp.find("EXPORT_JSON_START") +end = exp.find("EXPORT_JSON_END") +payload = json.loads(exp[start + len("EXPORT_JSON_START") : end].strip()) +items = payload.get("items") or [] +print(f"export {len(items)} items", flush=True) + +print("===== dylive deploy =====", flush=True) +dl = connect("107.173.30.245") +_, before = run(dl, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") +print("BEFORE\n", before, flush=True) +upload(dl) +code, out = run( + dl, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import yt_stream_key_db; print("py_ok")' +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api +""", +) +print(out, flush=True) +ensure_frontend_build(dl, "dylive") + +# import registry from dy export +sftp = dl.open_sftp() +with sftp.file("/tmp/yt_stream_keys_import.json", "w") as f: + f.write(json.dumps({"items": items}, ensure_ascii=False)) +sftp.close() +_, out2 = run( + dl, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db +# also snapshot local assign +print('assign_import', yt_stream_key_db.import_from_assign_groups(replace=False)) +data=json.load(open('/tmp/yt_stream_keys_import.json',encoding='utf-8')) +print('peer_import', yt_stream_key_db.import_payload(data.get('items') or [], replace=False)) +print('total', yt_stream_key_db.list_entries()['total']) +PY +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +curl -sk -m 15 -o /dev/null -w 'keys:%{http_code}\n' https://dylive.nomadro.com/youtube/keys +""", +) +print(out2, flush=True) +after_up = {ln.split()[0] for ln in out2.splitlines() if " Up " in ln and "neko" in ln} +before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln} +lost = before_up - after_up +if lost: + print("CRITICAL neko lost", lost) + raise SystemExit(2) +print("neko_ok", sorted(after_up)) +dl.close() +print("ALL_DONE") diff --git a/scripts/_deploy_stream_key_visible_dual.py b/scripts/_deploy_stream_key_visible_dual.py new file mode 100644 index 0000000..f67b512 --- /dev/null +++ b/scripts/_deploy_stream_key_visible_dual.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Deploy stream-key visible/copy UI+API to dy + dylive. Never touch Neko.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [ + ("dy", "108.174.50.68"), + ("dylive", "107.173.30.245"), +] +FILES = [ + "backend/app/yt_assign_db.py", + "backend/app/yt_stream_key_db.py", + "backend/app/youtube_relay_status.py", + "backend/app/main.py", + "frontend/src/lib/ytRelayStatus.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/app/youtube-relay-log/page.tsx", +] + + +def connect(host: str): + last = None + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=240, + ) + return c + except Exception as e: + last = e + print(f"ssh_retry {i} {host}: {e}", flush=True) + time.sleep(3 + i) + raise SystemExit(f"ssh fail {host}: {last}") + + +def run(c, cmd: str, t: int = 900) -> tuple[int, str]: + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + return o.channel.recv_exit_status(), out + + +for label, host in HOSTS: + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + _, before = run(c, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") + print("BEFORE\n" + before, flush=True) + sftp = c.open_sftp() + for rel in FILES: + local = ROOT / rel + assert local.is_file(), local + remote = f"/opt/douyinWEB/{rel}" + run(c, f"mkdir -p {'/'.join(remote.split('/')[:-1])}") + print("put", rel, flush=True) + sftp.put(str(local), remote) + sftp.close() + + code, out = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +print('groups', len(gs), 'with_key_field', sum(1 for g in gs if 'stream_key' in g and g.get('stream_key'))) +PY +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api + +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=2048 +if [ -d node_modules ]; then + npm run build +else + echo 'WARN skip build: no node_modules' +fi +systemctl restart douyinweb-web +sleep 3 +systemctl is-active douyinweb-web +echo '=== neko after ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +""", + t=900, + ) + print(out[-7000:] if len(out) > 7000 else out, flush=True) + if code != 0: + print(f"WARN exit {code}", flush=True) + + before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln} + _, after = run(c, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") + after_up = {ln.split()[0] for ln in after.splitlines() if " Up " in ln and "neko" in ln} + lost = before_up - after_up + print("AFTER\n" + after, flush=True) + if lost: + print("CRITICAL neko lost", lost, flush=True) + raise SystemExit(2) + print(f"neko_ok {label}", sorted(after_up), flush=True) + c.close() + +print("\nALL_DONE", flush=True) diff --git a/scripts/_deploy_studio_analytics.py b/scripts/_deploy_studio_analytics.py new file mode 100644 index 0000000..073fd04 --- /dev/null +++ b/scripts/_deploy_studio_analytics.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Deploy category filter + studio analytics DB + remote Neko telemetry.""" +import paramiko +import sys +from pathlib import Path + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/yt_studio_db.py", + "backend/app/yt_assign_db.py", + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/app/main.py", + "backend/app/db.py", + "backend/neko/live-ops-extension/background.js", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/lib/ytRelayStatus.ts", +] + + +def put(c, root, sudo=None): + sftp = c.open_sftp() + for rel in FILES: + src = LOCAL / rel + if not src.exists(): + print("MISS", rel, flush=True) + continue + tmp = f"/tmp/_stu_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(src.read_bytes()) + dst = f"{root}/{rel}" + parent = str(Path(dst).parent).replace("\\", "/") + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc \"mkdir -p {parent}; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + if sudo + else f"mkdir -p {parent}; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + ) + c.exec_command(cmd, timeout=30)[1].read() + print("ok", rel, flush=True) + sftp.close() + + +def build_restart(c, sudo=None, *, restart_ops_chrome=False): + inner = ( + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_stu.log 2>&1 && echo FE_OK || (tail -25 /tmp/fe_stu.log; echo FE_FAIL); " + "systemctl restart douyinweb-api douyinweb-web; " + "systemctl is-active douyinweb-api; systemctl is-active douyinweb-web; " + ) + if restart_ops_chrome: + inner += ( + "for i in 1 2 3 4 5 6; do " + "docker exec douyinweb-ops-neko-$i supervisorctl restart google-chrome >/dev/null 2>&1 || true; " + "done; echo OPS_CHROME_RESTARTED; " + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc '{inner}'" if sudo else inner + _i, o, e = c.exec_command(cmd, timeout=700) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("PHYS", flush=True) +put(p, "/opt/douyinWEB", "4669805") +build_restart(p, "4669805", restart_ops_chrome=True) +p.close() + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +print("VPS", flush=True) +put(v, "/opt/douyinWEB") +build_restart(v) +v.close() +print("DONE", flush=True) diff --git a/scripts/_deploy_studio_chrome_oom_fix.py b/scripts/_deploy_studio_chrome_oom_fix.py new file mode 100644 index 0000000..e575c7d --- /dev/null +++ b/scripts/_deploy_studio_chrome_oom_fix.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Deploy Studio Live Chrome OOM mitigations to dylive (and dy). Never recreate Neko.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" + +FILES = [ + ("backend/neko/browser-launch.sh", "/opt/douyinWEB/backend/neko/browser-launch.sh", 0o755), + ("backend/neko/live-ops-extension/content.js", "/opt/douyinWEB/backend/neko/live-ops-extension/content.js", 0o644), + ("backend/neko/live-ops-extension/manifest.json", "/opt/douyinWEB/backend/neko/live-ops-extension/manifest.json", 0o644), +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(12): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + print(f"retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def put(c, local: Path, remote: str, mode: int) -> None: + raw = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + sftp = c.open_sftp() + tmp = f"/tmp/{Path(remote).name}.oomfix" + with sftp.file(tmp, "wb") as f: + f.write(raw) + sftp.chmod(tmp, mode) + sftp.close() + _i, o, e = c.exec_command(f"cat {tmp} > {remote} && chmod {mode:o} {remote} && sed -i 's/\\r$//' {remote}", timeout=30) + o.channel.recv_exit_status() + print(f"wrote {remote} bytes={len(raw)}", flush=True) + + +REMOTE = r""" +set +e +# syntax check +sh -n /opt/douyinWEB/backend/neko/browser-launch.sh && echo launch_syntax_ok +grep -n 'renderer-process-limit=1\|prune_and_soft_reload\|max-old-space-size=160\|tameMedia\|1.4.0' \ + /opt/douyinWEB/backend/neko/browser-launch.sh \ + /opt/douyinWEB/backend/neko/live-ops-extension/content.js \ + /opt/douyinWEB/backend/neko/live-ops-extension/manifest.json | head -20 + +# Only touch running nekos — restart remounts browser-launch (fixes //deleted) without recreate +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort -V); do + echo "=== remount+restart chrome path: $n ===" + # Prefer chrome restart first if mount not deleted + del=$(docker exec "$n" sh -c 'cat /proc/self/mountinfo | grep browser-launch | grep -c "//deleted"' || true) + echo deleted=$del + if [ "${del:-0}" != "0" ]; then + docker restart "$n" + sleep 14 + else + docker exec "$n" sh -c ' + rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null + supervisorctl stop google-chrome || true + sleep 1 + supervisorctl start google-chrome + sleep 10 + supervisorctl status google-chrome + ' + fi + docker exec "$n" sh -c ' + grep -n "renderer-process-limit=1\|max-old-space-size=160\|prune_and_soft_reload" /etc/neko/browser-launch.sh | head -5 + curl -sS -m 4 http://127.0.0.1:9222/json/version | head -c 120; echo + ' + # Immediate tab prune (close google.com etc.) + docker exec "$n" sh -c 'DO_RELOAD=0 python3 - <<"PY" +import json, urllib.request +def tabs(): + with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as r: + return json.loads(r.read().decode()) +def close(tid): + try: urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2) + except Exception: pass +def is_live(u): + u=(u or "").lower(); return "studio.youtube.com" in u and "livestreaming" in u +def keep(u): + u=(u or "").lower() + if is_live(u): return True + if "accounts.google.com" in u and any(x in u for x in ("signin","accountchooser","identifier","challenge","servicelogin")): return True + return False +try: + pages=[t for t in tabs() if t.get("type")=="page"] +except Exception as e: + print("no_tabs", e); raise SystemExit(0) +live=[t for t in pages if is_live(t.get("url") or "")] +kid=(live[0].get("id") if live else "") or "" +closed=0 +for t in pages: + tid=t.get("id") or ""; url=t.get("url") or "" + if kid and tid==kid: continue + if is_live(url) and kid and tid!=kid: + close(tid); closed+=1; continue + if keep(url): continue + close(tid); closed+=1 +print("pruned", closed, "kept_live", bool(kid), "pages_left", len([t for t in tabs() if t.get("type")=="page"])) +for t in tabs(): + if t.get("type")=="page": + print("TAB", (t.get("url") or "")[:90]) +PY' + docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}}' "$n" +done +free -m | head -2 +echo HOST_DONE +""" + + +for label, host in (("dylive", "107.173.30.245"), ("dy", "108.174.50.68")): + print(f"\n######## {label} ########", flush=True) + c = connect(host) + for rel, remote, mode in FILES: + put(c, ROOT / rel, remote, mode) + _i, o, e = c.exec_command(REMOTE, timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_deploy_studio_evidence_first.py b/scripts/_deploy_studio_evidence_first.py new file mode 100644 index 0000000..9728eaf --- /dev/null +++ b/scripts/_deploy_studio_evidence_first.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Deploy studio evidence-first fix — progress prints, no silent wait.""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +FILES = [ + "backend/app/youtube_neko.py", + "frontend/src/components/YtRelayProStatusPanel.tsx", +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh {host} try {i}", flush=True) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + print("ok", flush=True) + return c + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + raise SystemExit(f"fail {host}") + + +def put(c, rel): + data = (ROOT / rel.replace("/", "\\")).read_bytes() + h = hashlib.sha256(data).hexdigest()[:12] + print(f" put {h} {rel}", flush=True) + sftp = c.open_sftp() + with sftp.file(f"/opt/douyinWEB/{rel}", "wb") as f: + f.write(data) + sftp.close() + return h + + +def run(c, cmd, timeout=120): + print(f"$ {cmd[:90]}...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + t0 = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - t0 > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.12) + print(f"\n[exit {chan.recv_exit_status()}]", flush=True) + + +def main(): + for name, host in HOSTS: + print(f"\n=== {name} ===", flush=True) + c = connect(host) + for rel in FILES: + put(c, rel) + run( + c, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +# smoke: evidence-first path exists +assert 'remote_live' in open('/opt/douyinWEB/backend/app/youtube_neko.py',encoding='utf-8',errors='replace').read() or True +src=open('/opt/douyinWEB/backend/app/youtube_neko.py',encoding='utf-8',errors='replace').read() +assert '_live_ui' in src and 'Evidence-first' in src +print('youtube_neko_ok') +PY +grep -n '远程 Neko\|remote_fallback\|Evidence-first\|_live_ui' /opt/douyinWEB/backend/app/youtube_neko.py /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -20 +systemctl restart douyinweb-api +sleep 2 +echo api=$(systemctl is-active douyinweb-api) +# FE: copy panel into .next is hard; rebuild only if node free — else note soft-refresh needs rebuild +# Quick: touch + optional next build in background skipped — use existing pattern: build on dy only if fast +""", + timeout=90, + ) + c.close() + # Build FE on dy then tar to dylive (panel text) + print("\n=== FE build on dy ===", flush=True) + c = connect("108.174.50.68") + run( + c, + r""" +pkill -f 'next build' 2>/dev/null || true +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build +systemctl restart douyinweb-web +echo web=$(systemctl is-active douyinweb-web) +tar -C /opt/douyinWEB/frontend -czf /tmp/next-evidence.tgz .next +ls -lh /tmp/next-evidence.tgz +""", + timeout=700, + ) + print("fetch next tarball...", flush=True) + sftp = c.open_sftp() + sftp.get("/tmp/next-evidence.tgz", str(ROOT / "scripts/_next-evidence.tgz")) + sftp.close() + c.close() + print("\n=== FE apply dylive ===", flush=True) + c = connect("107.173.30.245") + sftp = c.open_sftp() + local = ROOT / "scripts/_next-evidence.tgz" + size = local.stat().st_size + print(f"upload {size/1e6:.1f}MB", flush=True) + last = [0.0] + + def cb(sent, total): + now = time.time() + if now - last[0] >= 2 or sent == total: + print(f" {100*sent/total:.0f}%", flush=True) + last[0] = now + + sftp.put(str(local), "/tmp/next-evidence.tgz", callback=cb) + sftp.close() + run( + c, + r""" +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_ev +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_ev 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-evidence.tgz +systemctl start douyinweb-web +sleep 2 +echo web=$(systemctl is-active douyinweb-web) +""", + timeout=120, + ) + c.close() + print("ALL_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_studio_not_on_air_breaker.py b/scripts/_deploy_studio_not_on_air_breaker.py new file mode 100644 index 0000000..6ce97e7 --- /dev/null +++ b/scripts/_deploy_studio_not_on_air_breaker.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +"""Deploy Studio-not-on-air circuit breaker for YouTube relay auto flap.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("backend/app/youtube_relay_pipeline.py", "/tmp/_dy_yt_relay_pipeline.py"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +src = Path('/tmp/_dy_yt_relay_pipeline.py') +dst = Path('/opt/douyinWEB/backend/app/youtube_relay_pipeline.py') +dst.write_bytes(src.read_bytes().replace(b'\r\n', b'\n').replace(b'\r', b'\n')) +print('ok', dst, dst.stat().st_size) +PY +python3 -m py_compile /opt/douyinWEB/backend/app/youtube_relay_pipeline.py && echo py_ok +grep -n '_note_studio_not_on_air\|paused_studio\|studio_cooldown' /opt/douyinWEB/backend/app/youtube_relay_pipeline.py | head -20 +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service +curl -sS -m 8 http://127.0.0.1:8014/api/ping; echo +''' + + +def deploy(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_studio_breaker.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_studio_breaker.sh" if sudo else "bash /tmp/_dy_studio_breaker.sh" + _, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_deploy_studio_state_triad.py b/scripts/_deploy_studio_state_triad.py new file mode 100644 index 0000000..923e356 --- /dev/null +++ b/scripts/_deploy_studio_state_triad.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy Studio 开播/断播/停播 classification to VPS + physical.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + ("backend/app/youtube_neko.py", "/opt/douyinWEB/backend/app/youtube_neko.py"), + ("backend/app/youtube_relay_pipeline.py", "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py"), + ("backend/app/ops_neko.py", "/opt/douyinWEB/backend/app/ops_neko.py"), + ("backend/neko/cdp_studio_scrape.py", "/opt/douyinWEB/backend/neko/cdp_studio_scrape.py"), + ( + "backend/neko/live-ops-extension/content.js", + "/opt/douyinWEB/backend/neko/live-ops-extension/content.js", + ), +] + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def put_inplace(sftp, local: Path, remote: str) -> None: + """Overwrite existing file in-place (preserve inode for bind mounts).""" + data = local.read_bytes() + try: + with sftp.file(remote, "r+") as f: + f.write(data) + f.truncate(len(data)) + except OSError: + with sftp.file(remote, "wb") as f: + f.write(data) + + +def deploy(host, port, user, pwd, *, restart_api: bool, sync_ops_ext: bool) -> None: + print(f"\n=== {user}@{host}:{port} ===") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pwd, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for rel, remote in FILES: + put_inplace(sftp, ROOT / rel, remote) + print("put", remote) + sftp.close() + + def run(cmd: str, t: int = 90) -> str: + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + if sync_ops_ext: + # In-place into running ops-neko containers if extension is bind-mounted or copied. + print( + run( + r""" +for i in 1 2 3 4 5 6; do + name=douyinweb-ops-neko-$i + docker inspect "$name" >/dev/null 2>&1 || continue + # Prefer host bind path already updated; also copy into container path if present. + for p in /opt/douyinWEB/backend/neko/live-ops-extension/content.js; do + docker cp "$p" "$name:/home/neko/.config/chromium/live-ops-extension/content.js" 2>/dev/null || true + docker cp "$p" "$name:/etc/neko/live-ops-extension/content.js" 2>/dev/null || true + done + docker cp /opt/douyinWEB/backend/neko/cdp_studio_scrape.py "$name:/etc/neko/cdp_studio_scrape.py" 2>/dev/null || true +done +echo ops_ext_synced +""", + 60, + ).strip() + ) + + if restart_api: + unit = "douyinweb-api" + print("restart", run(f"systemctl restart {unit}; sleep 2; systemctl is-active {unit}", 50).strip()) + print( + "health", + run( + "curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo fail", + 20, + ).strip(), + ) + c.close() + + +def main() -> None: + deploy(*VPS, restart_api=True, sync_ops_ext=False) + deploy(*PHYS, restart_api=True, sync_ops_ext=True) + # Verify CDP classification on physical ops-1 + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*PHYS, timeout=30, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + r""" +# find venv +PY=/opt/douyinWEB/backend/.venv/bin/python +[ -x "$PY" ] || PY=python3 +docker exec douyinweb-ops-neko-1 python3 /etc/neko/cdp_studio_scrape.py 2>/dev/null | tail -1 +""", + timeout=40, + ) + print("\n=== CDP ops1 after deploy ===") + print((o.read() + e.read()).decode("utf-8", "replace")[:1500]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_studio_triad_phys.py b/scripts/_deploy_studio_triad_phys.py new file mode 100644 index 0000000..428bfd1 --- /dev/null +++ b/scripts/_deploy_studio_triad_phys.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Physical deploy for studio triad (sudo -S, in-place cat).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/neko/cdp_studio_scrape.py", + "backend/neko/live-ops-extension/content.js", +] + + +def main() -> None: + host, port, user, pw = "107.173.30.245", 4014, "eric", "4669805" + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + sftp = c.open_sftp() + pairs = [] + for rel in FILES: + tmp = f"/tmp/_triad_{rel.replace('/', '_')}" + with sftp.file(tmp, "wb") as f: + f.write((ROOT / rel).read_bytes()) + pairs.append((tmp, f"/opt/douyinWEB/{rel}")) + print("upload", rel) + sh = ["#!/bin/bash", "set -e"] + for tmp, dst in pairs: + sh.append(f"mkdir -p \"$(dirname '{dst}')\"") + # in-place overwrite preserves bind-mount inode when dst already exists + sh.append(f"cat '{tmp}' > '{dst}'") + sh.append(f"echo updated {dst}") + sh.append("systemctl restart douyinweb-api || systemctl restart douyinweb || true") + sh.append("sleep 3") + sh.append("systemctl is-active douyinweb-api || systemctl is-active douyinweb || true") + sh.append("curl -sS -m 5 -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health || true") + sh.append("grep -c encoder_lost /opt/douyinWEB/backend/neko/cdp_studio_scrape.py") + sh.append( + "docker cp /opt/douyinWEB/backend/neko/cdp_studio_scrape.py douyinweb-ops-neko-1:/etc/neko/cdp_studio_scrape.py 2>/dev/null || true" + ) + sh.append( + "docker exec douyinweb-ops-neko-1 python3 /etc/neko/cdp_studio_scrape.py 2>/dev/null | tail -1 | head -c 1200; echo" + ) + with sftp.file("/tmp/_deploy_triad.sh", "w") as f: + f.write("\n".join(sh) + "\n") + sftp.close() + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash /tmp/_deploy_triad.sh", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_time_slot_armed.py b/scripts/_deploy_time_slot_armed.py new file mode 100644 index 0000000..439488a --- /dev/null +++ b/scripts/_deploy_time_slot_armed.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""Deploy time_slot_armed switch for assign cards (API + FE).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("backend/app/yt_assign_db.py", "/tmp/_dy_yt_assign_db.py"), + ("backend/app/models.py", "/tmp/_dy_models.py"), + ("backend/app/main.py", "/tmp/_dy_main.py"), + ("frontend/src/components/YtAssignPanel.tsx", "/tmp/_dy_YtAssignPanel.tsx"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_dy_yt_assign_db.py','/opt/douyinWEB/backend/app/yt_assign_db.py'), + ('/tmp/_dy_models.py','/opt/douyinWEB/backend/app/models.py'), + ('/tmp/_dy_main.py','/opt/douyinWEB/backend/app/main.py'), + ('/tmp/_dy_YtAssignPanel.tsx','/opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx'), +] +for s,d in pairs: + p=Path(s); dst=Path(d) + dst.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('ok', dst, dst.stat().st_size) +PY +python3 -m py_compile /opt/douyinWEB/backend/app/yt_assign_db.py /opt/douyinWEB/backend/app/models.py /opt/douyinWEB/backend/app/main.py && echo py_ok +grep -n 'time_slot_armed\|group_eligible_for_time_slot' /opt/douyinWEB/backend/app/yt_assign_db.py | head -15 +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +# FE unit rebuild +if systemctl list-unit-files | grep -q douyinweb-web; then + cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -25 + systemctl restart douyinweb-web.service + sleep 3 + systemctl is-active douyinweb-web.service +fi +curl -sS -m 8 http://127.0.0.1:8014/api/ping; echo +''' + + +def deploy(label, host, port, user, pw, sudo=False, build_fe=True): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + script = REMOTE if build_fe else REMOTE.replace( + "if systemctl list-unit-files | grep -q douyinweb-web; then\n cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -25\n systemctl restart douyinweb-web.service\n sleep 3\n systemctl is-active douyinweb-web.service\nfi\n", + "systemctl restart douyinweb-web.service 2>/dev/null || true\n", + ) + with sftp.file("/tmp/_dy_slot_armed.sh", "w") as f: + f.write(script.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_slot_armed.sh" if sudo else "bash /tmp/_dy_slot_armed.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_deploy_timeslot_exclude.py b/scripts/_deploy_timeslot_exclude.py new file mode 100644 index 0000000..ed2d070 --- /dev/null +++ b/scripts/_deploy_timeslot_exclude.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy timeslot exclude list to physical + VPS (API + frontend build).""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/yt_assign_db.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/main.py", + "frontend/src/components/YtAssignPanel.tsx", + "backend/tests/test_timeslot_exclude.py", +] + + +def put(c: paramiko.SSHClient, root: str, sudo: str | None = None) -> None: + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_tex_{Path(rel).name}" + data = (LOCAL / rel).read_bytes() + with sftp.file(tmp, "wb") as f: + f.write(data) + dst = f"{root}/{rel}" + parent = str(Path(dst).parent).replace("\\", "/") + if sudo: + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc " + f"\"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + ) + else: + cmd = f"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + _, o, e = c.exec_command(cmd, timeout=40) + err = e.read().decode("utf-8", "replace") + if err.strip() and "password" not in err.lower(): + print("warn", rel, err[-200:], flush=True) + else: + print("ok", rel, flush=True) + sftp.close() + + +def build_restart(c: paramiko.SSHClient, sudo: str | None = None) -> None: + inner = ( + "cd /opt/douyinWEB/frontend && npm run build >/tmp/fe_tex.log 2>&1 " + "&& echo FE_OK || (tail -40 /tmp/fe_tex.log; echo FE_FAIL); " + "systemctl restart douyinweb-api douyinweb-web; " + "sleep 2; " + "systemctl is-active douyinweb-api; systemctl is-active douyinweb-web; " + "curl -sS -m 5 -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health || true" + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc {repr(inner)}" if sudo else inner + _, o, e = c.exec_command(cmd, timeout=900) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def verify(c: paramiko.SSHClient, sudo: str | None = None) -> None: + py = r""" +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +print('login', op.open(req, timeout=15).status) +raw=op.open('http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude', timeout=30).read() +p=json.loads(raw) +print('exclude_ok', p.get('ok'), 'count', p.get('count'), 'effective', p.get('effective_room_count')) +""" + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_v_tex.py", "w") as f: + f.write(py) + sftp.close() + cmd = f"echo '{sudo}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_v_tex.py" + else: + # write via stdin + cmd = "/opt/douyinWEB/backend/.venv/bin/python -" + if sudo: + _, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + else: + _, o, e = c.exec_command(cmd, timeout=60) + o.channel.sendall(py.encode()) + o.channel.shutdown_write() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def main() -> None: + # Physical first + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("===== PHYS =====", flush=True) + put(p, "/opt/douyinWEB", "4669805") + build_restart(p, "4669805") + verify(p, "4669805") + p.close() + + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("===== VPS =====", flush=True) + put(v, "/opt/douyinWEB") + build_restart(v) + verify(v) + v.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_timeslot_sticky_rotate.py b/scripts/_deploy_timeslot_sticky_rotate.py new file mode 100644 index 0000000..0f6db5f --- /dev/null +++ b/scripts/_deploy_timeslot_sticky_rotate.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy timeslot sticky-rotate fix to VPS API only (restart uvicorn).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "app" / "youtube_relay_pipeline.py" +REMOTE = "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py" + + +def main() -> None: + data = LOCAL.read_bytes() + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + # backup + try: + sftp.rename(REMOTE, REMOTE + ".bak_sticky_rotate") + except OSError: + pass + with sftp.file(REMOTE, "wb") as f: + f.write(data) + sftp.close() + _, o, e = c.exec_command( + "systemctl restart douyinweb-api && sleep 2 && systemctl is-active douyinweb-api && " + "curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || " + "curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/health || echo nohealth", + timeout=60, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + # wait one relay tick then show state + _, o2, e2 = c.exec_command( + r""" +sleep 8 +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, sqlite3, time +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +r=dict(con.execute('select status,error,source_url,source_room_id,anchor_name,ffmpeg_pid,recent_log,updated_at from yt_relay_states where group_id=?',(gid,)).fetchone() or {}) +print('status', r.get('status'), 'pid', r.get('ffmpeg_pid'), 'room', r.get('source_room_id'), 'anchor', r.get('anchor_name')) +print('url', r.get('source_url')) +print('err', (r.get('error') or '')[:120]) +log=r.get('recent_log') or '' +try: lines=json.loads(log) if str(log).startswith('[') else str(log).splitlines() +except: lines=[] +for ln in lines[-12:]: + print(ln) +PY +""", + timeout=40, + ) + print((o2.read() + e2.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_timeslot_sticky_rotate2.py b/scripts/_deploy_timeslot_sticky_rotate2.py new file mode 100644 index 0000000..8d9bd1a --- /dev/null +++ b/scripts/_deploy_timeslot_sticky_rotate2.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "app" / "youtube_relay_pipeline.py" +REMOTE = "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py" + + +def main() -> None: + data = LOCAL.read_bytes() + marker = b"rotate live list" + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + try: + remote = sftp.file(REMOTE, "rb").read() + except OSError: + remote = b"" + if marker not in remote: + print("uploading file…") + with sftp.file(REMOTE, "wb") as f: + f.write(data) + remote = data + else: + print("remote already has marker") + sftp.close() + print("local_bytes", len(data), "remote_has_marker", marker in remote) + + def run(cmd: str, t: int = 90) -> str: + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + print("active:", run("systemctl is-active douyinweb-api", 15).strip()) + print("restart…") + print(run("systemctl restart douyinweb-api", 45).strip()) + print("active2:", run("sleep 3; systemctl is-active douyinweb-api", 20).strip()) + print( + "health:", + run( + "curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo fail", + 20, + ).strip(), + ) + print( + "state:", + run( + r""" +sleep 12 +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import json, sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +r=dict(con.execute('select status,error,source_url,source_room_id,anchor_name,ffmpeg_pid,recent_log from yt_relay_states where group_id=?',(gid,)).fetchone() or {}) +print('status', r.get('status'), 'pid', r.get('ffmpeg_pid'), 'room', r.get('source_room_id'), 'anchor', r.get('anchor_name')) +log=r.get('recent_log') or '' +try: lines=json.loads(log) if str(log).startswith('[') else str(log).splitlines() +except: lines=[] +for ln in lines[-15:]: + print(ln) +PY +""", + 40, + ), + ) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_timeslot_test_fe.py b/scripts/_deploy_timeslot_test_fe.py new file mode 100644 index 0000000..0dc758b --- /dev/null +++ b/scripts/_deploy_timeslot_test_fe.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Redeploy YtAssignPanel FE after type fix; verify timeslot-test API.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=900): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-22000:] if len(out) > 22000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +sftp.put( + str(ROOT / "frontend/src/components/YtAssignPanel.tsx"), + "/tmp/YtAssignPanel.tsx", +) +sftp.close() +code, _ = run( + c, + r""" +set -euo pipefail +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx +cd /opt/douyinWEB/frontend +npm run build +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-web douyinweb-api +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 15 -b "$CS" -o /dev/null -w 'timeslot-test:%{http_code}\n' -X POST \ + http://127.0.0.1:8014/api/youtube/relay/timeslot-test \ + -H 'Content-Type: application/json' -d '{"enabled":false}' +curl -sS -m 15 -b "$CS" -o /dev/null -w 'timeslot-next:%{http_code}\n' -X POST \ + http://127.0.0.1:8014/api/youtube/relay/timeslot-test/next +echo DONE +""", +) +c.close() +raise SystemExit(code) diff --git a/scripts/_deploy_timeslot_test_rotate.py b/scripts/_deploy_timeslot_test_rotate.py new file mode 100644 index 0000000..3c568f4 --- /dev/null +++ b/scripts/_deploy_timeslot_test_rotate.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Deploy timeslot test rotate (API + FE) to dylive.nomadro.com.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + last = None + for i in range(6): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as ex: + last = ex + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit(last) + + +def run(c, cmd, t=600): + print(f"\n$ {cmd[:260]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-20000:] if len(out) > 20000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +files = [ + ("backend/app/db.py", "/tmp/db.py"), + ("backend/app/yt_assign_db.py", "/tmp/yt_assign_db.py"), + ("backend/app/youtube_relay_pipeline.py", "/tmp/youtube_relay_pipeline.py"), + ("backend/app/main.py", "/tmp/main.py"), + ("frontend/src/components/YtAssignPanel.tsx", "/tmp/YtAssignPanel.tsx"), +] +for rel, remote in files: + sftp.put(str(ROOT / rel), remote) +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail +install -m 0644 /tmp/db.py /opt/douyinWEB/backend/app/db.py +install -m 0644 /tmp/yt_assign_db.py /opt/douyinWEB/backend/app/yt_assign_db.py +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +install -m 0644 /tmp/main.py /opt/douyinWEB/backend/app/main.py +install -m 0644 /tmp/YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx + +cd /opt/douyinWEB/backend +./.venv/bin/python -m py_compile app/db.py app/yt_assign_db.py app/youtube_relay_pipeline.py app/main.py +./.venv/bin/python - <<'PY' +from app.yt_assign_db import overlay_timeslot_test_schedule +from app.youtube_relay_pipeline import YoutubeRelayPipeline +assert hasattr(YoutubeRelayPipeline, "set_timeslot_test_mode") +assert hasattr(YoutubeRelayPipeline, "timeslot_test_next") +print("api_ok", overlay_timeslot_test_schedule({"channels":[]}, test_on=False)["test_mode"]) +PY + +systemctl restart douyinweb-api +for i in $(seq 1 50); do + curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break + sleep 1 +done + +# FE rebuild +cd /opt/douyinWEB/frontend +if [ -f package.json ]; then + npm run build + systemctl restart douyinweb-web || systemctl restart douyinweb-frontend || true +fi + +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +echo '=== endpoints ===' +curl -sS -m 15 -b "$CS" -X POST http://127.0.0.1:8014/api/youtube/relay/timeslot-test \ + -H 'Content-Type: application/json' -d '{"enabled":false}' | python3 -c 'import sys,json;d=json.load(sys.stdin);print("test_off", d.get("settings",{}).get("youtube_relay_timeslot_test"))' +echo DONE +""", + t=900, +) +c.close() +raise SystemExit(code) diff --git a/scripts/_deploy_ui_busy_unlock.py b/scripts/_deploy_ui_busy_unlock.py new file mode 100644 index 0000000..e48bf25 --- /dev/null +++ b/scripts/_deploy_ui_busy_unlock.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +"""Deploy UI-only busy unlock (FE build). No backend/data changes.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("frontend/src/components/YtAssignPanel.tsx", "/tmp/_dy_YtAssignPanel.tsx"), + ("frontend/src/app/shorts/page.tsx", "/tmp/_dy_shorts_page.tsx"), + ("frontend/src/app/youtube/page.tsx", "/tmp/_dy_youtube_page.tsx"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_dy_YtAssignPanel.tsx','/opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx'), + ('/tmp/_dy_shorts_page.tsx','/opt/douyinWEB/frontend/src/app/shorts/page.tsx'), + ('/tmp/_dy_youtube_page.tsx','/opt/douyinWEB/frontend/src/app/youtube/page.tsx'), +] +for s,d in pairs: + p=Path(s); dst=Path(d) + dst.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('ok', dst.name, dst.stat().st_size) +PY +cd /opt/douyinWEB/frontend +npm run build 2>&1 | tail -25 +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service +curl -sS -o /dev/null -w 'youtube=%{http_code}\n' http://127.0.0.1:4015/youtube +curl -sS -o /dev/null -w 'shorts=%{http_code}\n' http://127.0.0.1:4015/shorts +''' + + +def deploy(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_ui_busy.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_ui_busy.sh" if sudo else "bash /tmp/_dy_ui_busy.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_deploy_ui_busy_unlock2.py b/scripts/_deploy_ui_busy_unlock2.py new file mode 100644 index 0000000..fb0f22a --- /dev/null +++ b/scripts/_deploy_ui_busy_unlock2.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""Deploy remaining UI busy-unlock pages.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + ("frontend/src/app/yt-long/page.tsx", "/tmp/_dy_yt_long.tsx"), + ("frontend/src/app/x/ClipsPanel.tsx", "/tmp/_dy_x_clips.tsx"), + ("frontend/src/app/youtube/page.tsx", "/tmp/_dy_youtube_page.tsx"), +] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +pairs=[ + ('/tmp/_dy_yt_long.tsx','/opt/douyinWEB/frontend/src/app/yt-long/page.tsx'), + ('/tmp/_dy_x_clips.tsx','/opt/douyinWEB/frontend/src/app/x/ClipsPanel.tsx'), + ('/tmp/_dy_youtube_page.tsx','/opt/douyinWEB/frontend/src/app/youtube/page.tsx'), +] +for s,d in pairs: + Path(d).write_bytes(Path(s).read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('ok', d) +PY +cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -22 +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service +''' + + +def deploy(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for local, remote in FILES: + data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file(remote, "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_ui_busy2.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_ui_busy2.sh" if sudo else "bash /tmp/_dy_ui_busy2.sh" + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +deploy("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +deploy("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_deploy_yt_long_quota_fix.py b/scripts/_deploy_yt_long_quota_fix.py new file mode 100644 index 0000000..729c244 --- /dev/null +++ b/scripts/_deploy_yt_long_quota_fix.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy yt_long_db.py + yt_long_pipeline.py to physical + VPS (API restart only).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/yt_long_db.py", + "backend/app/yt_long_pipeline.py", + "backend/tests/test_quota_defaults.py", +] + + +def put(c: paramiko.SSHClient, root: str, sudo: str | None = None) -> None: + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_ylq_{Path(rel).name}" + data = (LOCAL / rel).read_bytes() + with sftp.file(tmp, "wb") as f: + f.write(data) + dst = f"{root}/{rel}" + parent = str(Path(dst).parent).replace("\\", "/") + if sudo: + cmd = ( + f"echo '{sudo}' | sudo -S -p '' bash -lc " + f"\"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}\"" + ) + else: + cmd = f"mkdir -p '{parent}'; install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}" + _, o, e = c.exec_command(cmd, timeout=40) + err = (e.read() + o.read()).decode("utf-8", "replace") + print("ok" if not err.strip() or "password" in err.lower() else err[-200:], rel, flush=True) + sftp.close() + + +def restart_api(c: paramiko.SSHClient, sudo: str | None = None) -> None: + inner = ( + "systemctl restart douyinweb-api; sleep 2; systemctl is-active douyinweb-api; " + "curl -sS -m 8 -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health || true" + ) + cmd = f"echo '{sudo}' | sudo -S -p '' bash -lc {repr(inner)}" if sudo else inner + _, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def verify(c: paramiko.SSHClient, sudo: str | None = None) -> None: + py = r""" +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +print('login', op.open(req, timeout=20).status) +# save 9 +req2=urllib.request.Request('http://127.0.0.1:8014/api/yt-long/settings', data=json.dumps({'yt_long_channel_daily_max': 9}).encode(), headers={'Content-Type':'application/json'}, method='POST') +r=json.loads(op.open(req2, timeout=30).read()) +print('save_settings', r.get('settings',{}).get('yt_long_channel_daily_max'), 'top', r.get('channel_daily_max')) +# status again +st=json.loads(op.open('http://127.0.0.1:8014/api/yt-long/status', timeout=30).read()) +print('status', st.get('settings',{}).get('yt_long_channel_daily_max'), 'top', st.get('channel_daily_max')) +""" + sftp = c.open_sftp() + with sftp.file("/tmp/_v_ylq.py", "w") as f: + f.write(py) + sftp.close() + if sudo: + cmd = f"echo '{sudo}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_v_ylq.py" + else: + cmd = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_v_ylq.py" + _, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def main() -> None: + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("===== PHYS =====", flush=True) + put(p, "/opt/douyinWEB", "4669805") + restart_api(p, "4669805") + verify(p, "4669805") + p.close() + + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("===== VPS =====", flush=True) + put(v, "/opt/douyinWEB") + restart_api(v) + verify(v) + v.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_deploy_yt_long_upload_progress.py b/scripts/_deploy_yt_long_upload_progress.py new file mode 100644 index 0000000..d0f09a3 --- /dev/null +++ b/scripts/_deploy_yt_long_upload_progress.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deploy yt-long progress bar fix (uploaded-based) to dy + dylive.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "frontend" / "src" / "app" / "yt-long" / "page.tsx" +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] + +REMOTE = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +src=Path('/tmp/_yt_long_page.tsx') +dst=Path('/opt/douyinWEB/frontend/src/app/yt-long/page.tsx') +data=src.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n') +dst.write_bytes(data) +text=data.decode('utf-8','replace') +assert '上传 {progress}' in text or '上传 {progress}/' in text or 'progress = Number(ch.uploaded' in text +print('PUT_OK', dst, 'bytes', len(data)) +print('has_uploaded_progress', 'ch.uploaded' in text and 'progress' in text) +PY +cd /opt/douyinWEB/frontend +npm run build 2>&1 | tail -30 +systemctl restart douyinweb-web.service +sleep 2 +systemctl is-active douyinweb-web.service +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def deploy(label: str, host: str): + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + data = LOCAL.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file("/tmp/_yt_long_page.tsx", "wb") as f: + f.write(data) + with sftp.file("/tmp/_deploy_yt_long_progress.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_yt_long_progress.sh", timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")[-4000:], flush=True) + c.close() + + +def main(): + if not LOCAL.is_file(): + raise SystemExit(f"missing {LOCAL}") + for label, host in HOSTS: + deploy(label, host) + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_10_88_8001.py b/scripts/_diag_10_88_8001.py new file mode 100644 index 0000000..26a42cc --- /dev/null +++ b/scripts/_diag_10_88_8001.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Read-only: why http://10.88.0.8:8001 unreachable (WG related).""" +from __future__ import annotations + +import socket +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [ + ("dylive", "107.173.30.245", 22, "root", "Xiao4669805"), + ("dy", "108.174.50.68", 22, "root", "Xiao4669805"), +] + + +def ssh(label, host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + host, + port, + user, + pw, + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"{label} ssh_retry {i}: {e}", flush=True) + time.sleep(2) + return None + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +# local reachability from this Windows machine +print("=== local TCP 10.88.0.8:8001 ===", flush=True) +s = socket.socket() +s.settimeout(5) +try: + s.connect(("10.88.0.8", 8001)) + print("local_tcp: OK") +except Exception as e: + print(f"local_tcp: FAIL {e}") +finally: + s.close() + +for label, host, port, user, pw in HOSTS: + print(f"\n======== {label} {host} ========", flush=True) + c = ssh(label, host, port, user, pw) + if not c: + print("ssh fail") + continue + print( + run( + c, + r""" +set +e +echo '--- wg interfaces ---' +wg show 2>/dev/null | head -80 +echo +ip -br a 2>/dev/null | grep -E 'wg|10\.88|10\.8|82\.157' || true +echo '--- routes 10.88 ---' +ip route get 10.88.0.8 2>&1 || true +ip route | grep -E '10\.88|wg' || true +echo '--- ping/curl ---' +ping -c 2 -W 2 10.88.0.8 2>&1 | tail -5 +curl -sS -m 5 -o /dev/null -w 'curl_http=%{http_code} time=%{time_total}\n' http://10.88.0.8:8001/ || echo curl_fail +ss -lntp 2>/dev/null | grep -E ':8001\b|10\.88' || true +echo '--- systemd wg ---' +systemctl is-active 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null +echo '--- who is 10.88.0.8 locally? ---' +ip -br a | grep 10.88 || echo 'no 10.88 on this host' +""", + ), + flush=True, + ) + c.close() + +print("DONE") diff --git a/scripts/_diag_assign_neko_mounts.py b/scripts/_diag_assign_neko_mounts.py new file mode 100644 index 0000000..8ed3593 --- /dev/null +++ b/scripts/_diag_assign_neko_mounts.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +set -e +echo === host launch offline === +grep -n Offline /opt/douyinWEB/backend/neko/browser-launch.sh | head -5 +echo === host seed === +ls -la /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json +for n in 1 7 8; do + echo ===== mounts neko-$n ===== + docker inspect douyinweb-neko-$n --format '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}' | grep -E 'neko|policies|browser|tamper|live-ops' || true + echo ===== inside neko-$n ===== + docker exec douyinweb-neko-$n bash -lc 'echo ls_etc_neko; ls /etc/neko 2>&1; echo seed; ls /etc/neko/tampermonkey-seed/Default/Extensions 2>&1 | head; echo offline; grep -c Offline /etc/neko/browser-launch.sh; echo policy; ls -la /etc/opt/chrome/policies/managed 2>&1 | head; echo loadext; tr "\0" " " < /proc/$(pgrep -n -f "google-chrome.*--type=zygote" 2>/dev/null || pgrep -n google-chrome)/cmdline 2>/dev/null | grep -o "load-extension=[^ ]*" || (for p in /proc/[0-9]*; do c=$(tr "\0" " " < $p/cmdline 2>/dev/null); echo "$c" | grep -q "google-chrome" || continue; echo "$c" | grep -q -- "--type=" && continue; echo "$c" | grep -o "load-extension=[^ ]*" && break; done)' +done +echo === compose files === +ls -la /opt/douyinWEB/backend/data/neko/*.yml 2>/dev/null | head +ls -la /opt/douyinWEB/backend/data/neko/compose* 2>/dev/null | head +find /opt/douyinWEB/backend/data/neko -name '*compose*' 2>/dev/null | head +find /opt/douyinWEB -path '*neko*docker-compose*' 2>/dev/null | head +''' + +def run(label, host, port, user, pw, sudo): + print(f"\n########## {label} ##########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_mounts.sh", "wb") as f: + f.write(REMOTE.encode()) + sftp.close() + cmd = f"echo {pw} | sudo -S -p '' bash /tmp/_diag_mounts.sh" if sudo else "bash /tmp/_diag_mounts.sh" + _, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + +run("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True) +run("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) diff --git a/scripts/_diag_assign_picker_empty.py b/scripts/_diag_assign_picker_empty.py new file mode 100644 index 0000000..aedae4a --- /dev/null +++ b/scripts/_diag_assign_picker_empty.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Diagnose why assign 'new group' picker is empty on dy + dylive.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar +from collections import Counter + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +APP = ("hackrobot", "Xiao4669805@") +SITES = [ + ("dy", "https://dy.nomadro.live"), + ("dylive", "https://dylive.nomadro.com"), +] + + +def op_for(base: str): + cj = CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": APP[0], "password": APP[1]}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + op.open(req, timeout=45).read() + return op + + +def get(op, url: str): + with op.open(url, timeout=60) as r: + return json.loads(r.read().decode()) + + +for name, base in SITES: + print(f"\n======== {name} {base} ========", flush=True) + try: + op = op_for(base) + except Exception as e: + print("login fail", e) + continue + shorts = get(op, f"{base}/api/shorts/channels") + chans = shorts.get("channels") or shorts if isinstance(shorts, dict) else shorts + if isinstance(shorts, dict) and "channels" not in shorts: + # maybe list at root + for k, v in shorts.items(): + if isinstance(v, list) and v and isinstance(v[0], dict) and "id" in v[0]: + chans = v + break + if not isinstance(chans, list): + print("shorts unexpected", type(shorts), list(shorts)[:10] if isinstance(shorts, dict) else shorts) + chans = [] + auth = [c for c in chans if c.get("authorized") or c.get("has_refresh_token") or str(c.get("refresh_token") or "").strip()] + # authorized field from public API + auth2 = [c for c in chans if c.get("authorized")] + if auth2: + auth = auth2 + print(f"shorts total={len(chans)} authorized={len(auth)}") + + ag = get(op, f"{base}/api/youtube/assign/groups") + groups = ag.get("groups") or [] + print(f"assign groups={len(groups)}") + + used_pk = set() + used_yt = set() + for g in groups: + pk = str(g.get("channel_pk") or "").strip() + yt = str(g.get("youtube_channel_id") or "").strip() + if pk: + used_pk.add(pk) + if yt: + used_yt.add(yt) + + avail = [] + blocked = [] + for c in auth: + cid = str(c.get("id") or "") + yt = str(c.get("youtube_channel_id") or "").trim() if False else str(c.get("youtube_channel_id") or "").strip() + why = [] + if cid in used_pk: + why.append("pk") + if yt and yt in used_yt: + why.append("yt") + if why: + blocked.append((c.get("name"), cid[:8], yt[:20], "+".join(why))) + else: + avail.append(c.get("name")) + + print(f"available_for_new={len(avail)} -> {avail[:10]}") + print(f"blocked={len(blocked)}") + + # duplicates by yt / name / pk + yt_c = Counter(str(g.get("youtube_channel_id") or "") for g in groups if g.get("youtube_channel_id")) + name_c = Counter(str(g.get("name") or "") for g in groups) + pk_c = Counter(str(g.get("channel_pk") or "") for g in groups if g.get("channel_pk")) + print("dup yt:", {k: v for k, v in yt_c.items() if v > 1}) + print("dup name:", {k: v for k, v in name_c.items() if v > 1}) + print("dup pk:", {k: v for k, v in pk_c.items() if v > 1}) + + print("--- groups ---") + for g in groups: + print( + f" {(g.get('name') or '')[:28]:28} pk={(g.get('channel_pk') or '-')[:8]} yt={(g.get('youtube_channel_id') or '-')[:22]} sk={len(str(g.get('stream_key') or ''))} neko={g.get('neko_instance_id')} en={g.get('neko_enabled')}" + ) + + print("--- authorized shorts not matching any group name ---") + gnames = {str(g.get("name") or "").lower() for g in groups} + for c in auth: + nm = str(c.get("name") or "") + if nm.lower() not in gnames: + print(" orphan shorts?", nm, c.get("youtube_channel_id"), "blocked" if any(b[0]==nm for b in blocked) else "AVAIL") + +print("\nDONE") diff --git a/scripts/_diag_caddy_api_route.py b/scripts/_diag_caddy_api_route.py new file mode 100644 index 0000000..d8470b2 --- /dev/null +++ b/scripts/_diag_caddy_api_route.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Read-only: how Caddy routes /api vs page on dy.nomadro.com.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = r''' +grep -nE 'handle |reverse_proxy|api|4015|18014|10\.8\.0\.2:4015|10\.8\.0\.2:8014' /etc/caddy/sites/dy.nomadro.com.caddy | head -80 +echo '--- probe ---' +curl -sS -m 8 -o /dev/null -w 'api_cover=%{http_code}\n' -b 'dy_session=test' https://dy.nomadro.com/api/sessions/f675f45e-bfe4-482e-a1f6-16c994c25f3e/cover +curl -sS -m 8 -o /dev/null -w 'douyin_covers_jpg=%{http_code}\n' https://dy.nomadro.com/douyin-covers/covers/f675f45e-bfe4-482e-a1f6-16c994c25f3e.jpg +''' +_i, o, e = c.exec_command(cmd, timeout=40) +while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) +sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) +sys.stdout.flush() +c.close() +print("DONE", flush=True) diff --git a/scripts/_diag_cover_cookie.py b/scripts/_diag_cover_cookie.py new file mode 100644 index 0000000..65199bc --- /dev/null +++ b/scripts/_diag_cover_cookie.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Read-only: does /api/sessions/.../cover work with cookie only (like )?""" +from __future__ import annotations + +import sys + +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +BASE = "https://dy.nomadro.com" +with httpx.Client(follow_redirects=False, timeout=25) as cl: + r = cl.post(f"{BASE}/api/auth/login", json={"username": "hackrobot", "password": "Xiao4669805@"}) + print("login", r.status_code, "set-cookie", r.headers.get("set-cookie", "")[:120], flush=True) + print("cookies", cl.cookies.jar, flush=True) + # list live sessions with bearer from body AND cookies + body = r.json() + token = body.get("token") or "" + rr = cl.get(f"{BASE}/api/sessions", headers={"Authorization": f"Bearer {token}"}) + sessions = (rr.json() or {}).get("sessions") or [] + live = [s for s in sessions if not s.get("ended_at")][:3] + print("live", len(live), flush=True) + for s in live: + sid = s["id"] + path = f"/api/sessions/{sid}/cover" + # cookie only + a = cl.get(f"{BASE}{path}") + print(f"cookie-only {path} -> {a.status_code} ctype={a.headers.get('content-type')} len={len(a.content)}", flush=True) + # no cookie no auth + with httpx.Client(timeout=15) as bare: + b = bare.get(f"{BASE}{path}") + print(f"anon {path} -> {b.status_code}", flush=True) + # s3-style if any absolute + for k in ("cover_url", "avatar_url", "cover_proxy_url"): + u = s.get(k) + if u and str(u).startswith("http"): + c = cl.get(u) + print(f"abs {k} {u[:80]} -> {c.status_code}", flush=True) + + # douyin-covers probe via API-derived public urls if health s3 public_base used + # try list objects? skip + print("douyin-covers sample", flush=True) + d = cl.get("https://dy.nomadro.com/douyin-covers/") + print("douyin-covers/", d.status_code, flush=True) + +print("DONE", flush=True) diff --git a/scripts/_diag_cover_cookie2.py b/scripts/_diag_cover_cookie2.py new file mode 100644 index 0000000..9f6f2d3 --- /dev/null +++ b/scripts/_diag_cover_cookie2.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Read-only: cover with cookie only (img behavior).""" +from __future__ import annotations + +import sys + +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +BASE = "https://dy.nomadro.com" +with httpx.Client(follow_redirects=False, timeout=25) as cl: + r = cl.post(f"{BASE}/api/auth/login", json={"username": "hackrobot", "password": "Xiao4669805@"}) + print("login", r.status_code, "cookie", bool(cl.cookies.get("dy_session")), flush=True) + print("body keys", list((r.json() or {}).keys()), flush=True) + rr = cl.get(f"{BASE}/api/sessions") + print("sessions", rr.status_code, flush=True) + data = rr.json() if rr.status_code == 200 else {} + sessions = data.get("sessions") or [] + live = [s for s in sessions if not s.get("ended_at")][:5] + print("live", len(live), flush=True) + for s in live: + sid = s["id"] + path = f"/api/sessions/{sid}/cover" + a = cl.get(f"{BASE}{path}") + print( + f"{s.get('anchor_name')}: cover_url={s.get('cover_url')!r} " + f"cookie-get -> {a.status_code} ctype={a.headers.get('content-type')} bytes={len(a.content)}", + flush=True, + ) + # absolute s3-style covers among recent + abs_n = 0 + for s in sessions[:30]: + for k in ("cover_url", "avatar_url", "cover_proxy_url"): + u = s.get(k) + if isinstance(u, str) and u.startswith("http"): + c = cl.get(u) + print(f"ABS {k} {u[:90]} -> {c.status_code}", flush=True) + abs_n += 1 + if abs_n >= 5: + break + if abs_n >= 5: + break + print("abs_found", abs_n, flush=True) + d = cl.get("https://dy.nomadro.com/douyin-covers/") + print("douyin-covers/", d.status_code, flush=True) + +print("DONE", flush=True) diff --git a/scripts/_diag_cover_paths.py b/scripts/_diag_cover_paths.py new file mode 100644 index 0000000..63b00a7 --- /dev/null +++ b/scripts/_diag_cover_paths.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Read-only: how live session covers are stored on physical API.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = r''' +echo 4669805 | sudo -S -p '' bash -lc ' +cd /opt/douyinWEB/backend +.venv/bin/python - </dev/null || echo err) + echo "$code $u" +done +echo '-- caddy dy site snippets --' +grep -nE 'douyin-covers|ops-neko|/neko/|8333|18200|10\.8\.0\.2' /etc/caddy/sites/*.caddy 2>/dev/null | head -80 +echo '-- local weed --' +ss -lntup 2>/dev/null | grep -E ':8333|:18200|:9200' || netstat -lntup 2>/dev/null | grep -E ':8333|:18200|:9200' +curl -sS -m 5 -o /dev/null -w 'vps_weed_8333=%{http_code}\n' http://127.0.0.1:8333/ 2>/dev/null +curl -sS -m 5 -o /dev/null -w 'frp_aux_18333=%{http_code}\n' http://127.0.0.1:18333/ 2>/dev/null +""", + 90, + ) +) +v.close() + +print("===== PHYSICAL probes =====") +p = ssh("107.173.30.245", 4014, "eric", "4669805") +print( + run( + p, + r"""echo '4669805' | sudo -S -p '' bash -lc ' +set +e +ss -lntup 2>/dev/null | grep -E ":8333|:18200|:9200" | head -20 +docker ps -a --format "{{.Names}} {{.Status}} {{.Ports}}" 2>/dev/null | grep -E "ops-neko|douyinweb-neko" | head -20 +curl -sS -m 5 --noproxy "*" -o /dev/null -w "local_weed=%{http_code}\n" http://127.0.0.1:8333/ +curl -sS -m 5 --noproxy "*" -o /dev/null -w "opsneko1=%{http_code}\n" http://127.0.0.1:18200/ +curl -sS -m 5 --noproxy "*" -o /dev/null -w "neko1=%{http_code}\n" http://127.0.0.1:9200/ +# sample cover from db +python3 - <<"PY" +import sqlite3, json +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +rows=c.execute("select id, cover_url, cover_path from sessions where cover_url!=\"\" or cover_path!=\"\" order by started_at desc limit 3").fetchall() +print("sessions_covers", rows) +# try rooms +try: + print("settings s3", [(k, str(v)[:80]) for k,v in c.execute("select key,value from kv_settings where key like \"%s3%\" or key like \"%cover%\" or key like \"%S3%\"").fetchall()][:20]) +except Exception as e: + print(e) +c.close() +PY +' +""", + 90, + ) +) +p.close() diff --git a/scripts/_diag_dual_deploy_avatars_neko.py b/scripts/_diag_dual_deploy_avatars_neko.py new file mode 100644 index 0000000..ffc358e --- /dev/null +++ b/scripts/_diag_dual_deploy_avatars_neko.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare deployed revisions on both VPS vs local key files.""" +from __future__ import annotations + +import hashlib +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +PASS = "Xiao4669805" +FILES = [ + "backend/app/session_auth.py", + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/yt_assign_db.py", + "frontend/src/lib/api.js", + "frontend/src/components/YtAssignPanel.tsx", +] +REMOTE_SCRIPT = r""" +set +e +cd /opt/douyinWEB +echo "git=$(git rev-parse --short HEAD 2>/dev/null) branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)" +echo "api=$(systemctl is-active douyinweb-api) web=$(systemctl is-active douyinweb-web)" +echo "api_mtime=$(stat -c %y /opt/douyinWEB/backend/app/session_auth.py 2>/dev/null)" +echo "fe_panel_mtime=$(stat -c %y /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx 2>/dev/null)" +echo "next_mtime=$(stat -c %y /opt/douyinWEB/frontend/.next/BUILD_ID 2>/dev/null)" +python3 - <<'PY' +import hashlib, pathlib +files=[ + 'backend/app/session_auth.py', + 'backend/app/youtube_neko.py', + 'backend/app/youtube_relay_pipeline.py', + 'backend/app/yt_assign_db.py', + 'frontend/src/lib/api.js', + 'frontend/src/components/YtAssignPanel.tsx', +] +root=pathlib.Path('/opt/douyinWEB') +for rel in files: + p=root/rel + if not p.exists(): + print('MISSING', rel); continue + h=hashlib.sha256(p.read_bytes()).hexdigest()[:12] + print(h, rel) +PY +echo '--- markers ---' +grep -n '物理机配对\|默认停止\|Live 页\|目录为空' /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx 2>/dev/null | head -30 +grep -Rni '物理机配对\|目录为空' /opt/douyinWEB/frontend/src/components /opt/douyinWEB/frontend/src/app/neko 2>/dev/null | head -30 +echo '--- channel thumbs ---' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + print('tables', [r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND (name LIKE '%assign%' OR name LIKE 'yt_%')").fetchall()]) + for table in ('yt_oauth_channels','yt_channels','youtube_channels','yt_assign_channels','shorts_channels'): + try: + cols=[r[1] for r in conn.execute(f'PRAGMA table_info({table})').fetchall()] + print(table, 'cols', cols[:20]) + except Exception as e: + print(table, 'no', e) + # try common queries + queries=[ + ("SELECT id, title, substr(coalesce(thumb_url,thumbnail_url,''),1,100) FROM yt_oauth_channels LIMIT 8",), + ("SELECT id, title, substr(coalesce(thumb_url,''),1,100) FROM shorts_channels LIMIT 8",), + ("SELECT id, name, substr(coalesce(thumbnail_url,''),1,100) FROM yt_assign_groups LIMIT 8",), + ] + for (sql,) in queries: + try: + rows=conn.execute(sql).fetchall() + print('OK', sql[:50], 'n=', len(rows)) + for r in rows: print(' ', r) + except Exception as e: + print('FAIL', sql[:40], e) +PY +""" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail " + host) + + +def run(c, cmd, timeout=120): + _i, o, e = c.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("LOCAL", flush=True) +for rel in FILES: + path = rf"c:\Users\admin\Desktop\douyinWEB\{rel.replace('/', chr(92))}" + data = open(path, "rb").read() + print(f" {hashlib.sha256(data).hexdigest()[:12]} {rel}", flush=True) + +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + print(run(c, REMOTE_SCRIPT), flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_dual_deploy_bugs.py b/scripts/_diag_dual_deploy_bugs.py new file mode 100644 index 0000000..42d5aaf --- /dev/null +++ b/scripts/_diag_dual_deploy_bugs.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Read-only dual-deploy bug hunt: dylive (VPS) vs dy (physical via WG).""" +from __future__ import annotations + +import json +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def ssh(host, port, user, pw, retries=8): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + pw, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + return c + except Exception as ex: + last = ex + print(f"ssh retry {user}@{host}:{port} {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(3) + raise SystemExit(f"ssh failed {user}@{host}:{port}: {last}") + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + return code, out + + +def section(title: str): + print(f"\n===== {title} =====", flush=True) + + +def probe_public(): + section("PUBLIC HTTP") + urls = [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/", + "https://dylive.nomadro.com/covers", + "https://dylive.nomadro.com/covers/", + "https://dylive.nomadro.com/login", + "https://dylive.nomadro.com/neko/1/", + "https://dylive.nomadro.com/ops-neko/1/", + "https://dylive.nomadro.com/youtube", + "https://dylive.nomadro.com/network", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.com/covers", + "https://dy.nomadro.com/covers/", + "https://dy.nomadro.com/login", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/ops-neko/1/", + "https://dy.nomadro.com/youtube", + "https://dy.nomadro.com/network", + "https://dy.nomadro.cn/api/health", + "https://dy.nomadro.cn/", + ] + with httpx.Client(follow_redirects=False, timeout=25, verify=True) as cl: + for url in urls: + try: + r = cl.get(url) + loc = r.headers.get("location", "") + body = (r.text or "")[:120].replace("\n", " ") + # flag leaked loopback / WG IPs in redirects or body + leak = "" + for bad in ("127.0.0.1", "10.8.0.2", "10.9.0.2", ":8014", ":4015"): + if bad in loc or bad in body: + leak = f" LEAK={bad}" + break + print( + f"{r.status_code} {url} loc={loc[:100]!r}{leak} body={body[:80]!r}", + flush=True, + ) + except Exception as ex: + print(f"ERR {url} {type(ex).__name__}: {ex}", flush=True) + + +def probe_vps(c): + section("VPS (dylive) services + env + caddy") + cmd = r""" +set +e +echo '--- units ---' +systemctl is-active caddy sing-box frpp 'wg-quick@wg-dy' docker douyinweb-api douyinweb-web 2>/dev/null +systemctl is-enabled caddy sing-box frpp 'wg-quick@wg-dy' 2>/dev/null +echo '--- listen ---' +ss -lntp 2>/dev/null | grep -E ':4015|:8014|:443|:80|:51820|:4014|:7000' | head -40 +echo '--- wg ---' +wg show wg-dy 2>/dev/null | head -25 +ping -c 2 -W 2 10.8.0.2 2>&1 | tail -4 +echo '--- via wg health ---' +curl -sS -m 8 -o /dev/null -w 'wg_api=%{http_code}\n' http://10.8.0.2:8014/api/health +curl -sS -m 8 -o /dev/null -w 'wg_web=%{http_code}\n' http://10.8.0.2:4015/ +curl -sS -m 8 -o /dev/null -w 'loop_api=%{http_code}\n' http://127.0.0.1:8014/api/health +curl -sS -m 8 -o /dev/null -w 'loop_web=%{http_code}\n' http://127.0.0.1:4015/ +echo '--- dylive env (filtered) ---' +grep -E '^(DY_|DOMAIN|PUBLIC)' /etc/douyinweb.env 2>/dev/null | sed -E 's/(PASSWORD|SECRET|TOKEN|KEY)=.*/\1=***/' | head -60 +systemctl show douyinweb-api -p Environment 2>/dev/null | tr ' ' '\n' | grep -E '^DY_|^DOMAIN|^PUBLIC' | sed -E 's/(PASSWORD|SECRET|TOKEN|KEY)=.*/\1=***/' | head -40 +echo '--- host profile ---' +curl -sS -m 8 http://127.0.0.1:8014/api/ops/host-profile 2>/dev/null | head -c 800; echo +echo '--- git ---' +cd /opt/douyinWEB 2>/dev/null && git log -1 --oneline; git status -sb | head -5 +echo '--- caddy sites ---' +ls -la /etc/caddy/sites/ 2>/dev/null +echo '--- dylive.caddy key lines ---' +grep -nE 'reverse_proxy|handle |header_up|127\.0\.0\.1|10\.8\.0' /etc/caddy/sites/dylive.nomadro.com.caddy 2>/dev/null | head -50 +echo '--- dy.com.caddy key lines ---' +grep -nE 'reverse_proxy|handle |header_up|127\.0\.0\.1|10\.8\.0|4014|920' /etc/caddy/sites/dy.nomadro.com.caddy 2>/dev/null | head -80 +echo '--- covers redirect leak check ---' +curl -sS -m 10 -D- -o /dev/null http://127.0.0.1:8014/covers 2>&1 | head -20 +curl -sS -m 10 -D- -o /dev/null -H 'Host: dylive.nomadro.com' http://127.0.0.1:8014/covers 2>&1 | head -20 +echo '--- neko sample ---' +curl -sS -m 8 -o /dev/null -w 'neko1=%{http_code}\n' -H 'Host: dylive.nomadro.com' http://127.0.0.1:4015/neko/1/ +docker ps --format '{{.Names}} {{.Status}}' 2>/dev/null | grep -iE 'neko|dylive|ops' | head -30 +echo '--- rooms count ---' +curl -sS -m 8 'http://127.0.0.1:8014/api/rooms?limit=1' 2>/dev/null | head -c 300; echo +""" + code, out = run(c, cmd, 150) + print(out, flush=True) + return code + + +def probe_physical(c): + section("PHYSICAL (dy) via FRP:4014") + cmd = r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +echo "--- units ---" +systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-s3 douyinweb-youtube 2>/dev/null +systemctl is-active wg-quick@wg-dy wg-quick@wg-dy-cn docker 2>/dev/null +echo "--- listen ---" +ss -lntp 2>/dev/null | grep -E ":4015|:8014|:8092|:8333|:920|:51820|:51821" | head -40 +echo "--- wg ---" +wg show wg-dy 2>/dev/null | head -20 +wg show wg-dy-cn 2>/dev/null | head -20 +ping -c 2 -W 2 10.8.0.1 2>&1 | tail -4 +ping -c 2 -W 2 10.9.0.1 2>&1 | tail -4 +echo "--- loop health ---" +curl -sS -m 8 --noproxy "*" -o /dev/null -w "api=%{http_code}\n" http://127.0.0.1:8014/api/health +curl -sS -m 8 --noproxy "*" -o /dev/null -w "web=%{http_code}\n" http://127.0.0.1:4015/ +echo "--- bind check (must be 0.0.0.0 for physical) ---" +ss -lntp 2>/dev/null | grep -E "8014|4015" | head -10 +echo "--- env ---" +grep -E "^(DY_|DOMAIN|PUBLIC)" /etc/douyinweb.env 2>/dev/null | sed -E "s/(PASSWORD|SECRET|TOKEN|KEY)=.*/\1=***/" | head -80 +systemctl show douyinweb-api -p Environment 2>/dev/null | tr " " "\n" | grep -E "^DY_|^DOMAIN|^PUBLIC" | sed -E "s/(PASSWORD|SECRET|TOKEN|KEY)=.*/\1=***/" | head -50 +echo "--- host profile ---" +curl -sS -m 8 --noproxy "*" http://127.0.0.1:8014/api/ops/host-profile 2>/dev/null | head -c 800; echo +echo "--- git ---" +git config --global --add safe.directory /opt/douyinWEB 2>/dev/null || true +cd /opt/douyinWEB && git log -1 --oneline; git status -sb | head -5 +echo "--- covers redirect ---" +curl -sS -m 10 --noproxy "*" -D- -o /dev/null http://127.0.0.1:8014/covers 2>&1 | head -20 +curl -sS -m 10 --noproxy "*" -D- -o /dev/null -H "Host: dy.nomadro.com" http://127.0.0.1:8014/covers 2>&1 | head -20 +echo "--- next covers page vs static ---" +curl -sS -m 10 --noproxy "*" -o /dev/null -w "covers_page=%{http_code} loc=%{redirect_url}\n" -D- http://127.0.0.1:4015/covers 2>&1 | head -25 +echo "--- rooms ---" +curl -sS -m 8 --noproxy "*" "http://127.0.0.1:8014/api/rooms?limit=1" 2>/dev/null | head -c 300; echo +echo "--- neko docker ---" +docker ps --format "{{.Names}} {{.Status}} {{.Ports}}" 2>/dev/null | grep -iE "neko|ops" | head -40 +echo "--- neko nat/env sample ---" +docker inspect $(docker ps -q --filter name=neko 2>/dev/null | head -1) 2>/dev/null | grep -E "NAT1TO1|NEKO_|DY_" | head -30 +echo "--- disk/mem ---" +df -h / /opt 2>/dev/null | head -5 +free -h | head -3 +uptime +' +""" + code, out = run(c, cmd, 180) + print(out, flush=True) + return code + + +def compare_apis(): + section("API PARITY (public)") + paths = [ + "/api/health", + "/api/ops/host-profile", + "/api/rooms?limit=1", + "/api/network", + "/api/yt/relay/status", + "/api/ops-neko/catalog", + ] + with httpx.Client(follow_redirects=False, timeout=25, verify=True) as cl: + for path in paths: + for base in ("https://dylive.nomadro.com", "https://dy.nomadro.com"): + url = base + path + try: + r = cl.get(url) + snippet = (r.text or "")[:200].replace("\n", " ") + # redact secrets-ish + if "password" in snippet.lower() or "secret" in snippet.lower(): + snippet = snippet[:40] + "...[redacted]" + print(f"{r.status_code} {url} -> {snippet}", flush=True) + except Exception as ex: + print(f"ERR {url} {ex}", flush=True) + + +def main() -> int: + probe_public() + compare_apis() + + section("SSH VPS") + v = ssh(*VPS) + try: + probe_vps(v) + finally: + v.close() + + section("SSH PHYSICAL") + p = ssh(*PHYS) + try: + probe_physical(p) + finally: + p.close() + + print("\nDONE", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_diag_dual_deploy_deep.py b/scripts/_diag_dual_deploy_deep.py new file mode 100644 index 0000000..41131af --- /dev/null +++ b/scripts/_diag_dual_deploy_deep.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Deep read-only probe for WG/Caddy/FRP and failed units.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + last = None + for i in range(8): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + pw, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + return c + except Exception as ex: + last = ex + print(f"retry {i} {ex}", flush=True) + time.sleep(3) + raise SystemExit(last) + + +def run(c, cmd, t=150): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +def main(): + v = ssh("107.173.30.245", 22, "root", "Xiao4669805") + print("===== VPS deep =====", flush=True) + run( + v, + r""" +set +e +echo '--- wg handshake ---' +wg show wg-dy +echo '--- dy.caddy first 80 proxy lines ---' +grep -nE 'reverse_proxy|handle /' /etc/caddy/sites/dy.nomadro.com.caddy | head -100 +echo '--- count targets ---' +echo -n '10.8.0.2 count='; grep -c '10.8.0.2' /etc/caddy/sites/dy.nomadro.com.caddy +echo -n '127.0.0.1 count='; grep -c '127.0.0.1' /etc/caddy/sites/dy.nomadro.com.caddy +echo '--- frp aux systemd ---' +systemctl list-units '*frp*' --all --no-pager | head -30 +ls /etc/systemd/system/*frp* /etc/systemd/system/*dy*aux* 2>/dev/null +ss -lntp | grep -E ':(4015|8014|9200|9201|18200|18201)\b' | head -30 +echo '--- public vs wg ---' +curl -sS -m 15 -o /dev/null -w 'dy_public=%{http_code} t=%{time_total}\n' https://dy.nomadro.com/api/health +curl -sS -m 8 -o /dev/null -w 'wg_direct=%{http_code}\n' http://10.8.0.2:8014/api/health +echo '--- dylive neko ---' +docker ps --format '{{.Names}} {{.Status}}' | grep -iE 'neko|ops' | head -40 +echo '--- dylive units ---' +systemctl is-active douyinweb-youtube douyinweb-pb douyinweb-s3 +ss -lntp | grep -E ':(8020|8092|8333)\b' | head +echo '--- dylive health ---' +curl -sS -m 8 http://127.0.0.1:8014/api/health; echo +echo '--- ops-neko headers ---' +curl -sSI -m 8 https://dylive.nomadro.com/ops-neko/1/ 2>&1 | head -20 +curl -sSI -m 8 https://dylive.nomadro.com/ops-neko/1 2>&1 | head -20 +curl -sSI -m 8 https://dy.nomadro.com/ops-neko/1/ 2>&1 | head -20 +echo '--- dylive.caddy ops-neko ---' +grep -nE 'ops-neko|neko' /etc/caddy/sites/dylive.nomadro.com.caddy | head -40 +echo '--- dy.caddy ops-neko ---' +grep -nE 'ops-neko|neko|1820|920' /etc/caddy/sites/dy.nomadro.com.caddy | head -60 +""", + ) + v.close() + + p = ssh("107.173.30.245", 4014, "eric", "4669805") + print("===== PHYS deep =====", flush=True) + run( + p, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +echo "--- pb/youtube ---" +systemctl is-active douyinweb-pb douyinweb-youtube +systemctl status douyinweb-pb --no-pager -l | head -45 +echo +systemctl status douyinweb-youtube --no-pager -l | head -45 +echo "--- wg-dy ---" +wg show wg-dy +ip -4 addr show wg-dy +wg show wg-dy latest-handshakes +wg show wg-dy-cn latest-handshakes +ip route get 10.8.0.1 +ping -c 3 -W 2 10.8.0.1 | tail -5 +echo "--- frp ---" +systemctl list-units "*frp*" --all --no-pager | head +ps aux | grep -i frp | grep -v grep | head +echo "--- health ---" +curl -sS -m 8 --noproxy "*" http://127.0.0.1:8014/api/health; echo +echo "--- pb journal ---" +journalctl -u douyinweb-pb -n 40 --no-pager +echo "--- youtube journal ---" +journalctl -u douyinweb-youtube -n 40 --no-pager +echo "--- neko1 ICE ---" +docker inspect douyinweb-neko-1 --format "{{json .Config.Env}}" 2>/dev/null | tr "," "\n" | grep -E "NAT1TO1|ICELITE|UDPMUX|EPR|TCPMUX" +echo "--- who listens 8092 8020 ---" +ss -lntp | grep -E ":(8092|8020|8333)\b" | head +' +""", + ) + p.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dual_deploy_pb_neko.py b/scripts/_diag_dual_deploy_pb_neko.py new file mode 100644 index 0000000..d0b05de --- /dev/null +++ b/scripts/_diag_dual_deploy_pb_neko.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + host, + port, + user, + pw, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + return c + except Exception as ex: + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print("===== VPS PB / neko / frp-aux =====", flush=True) +run( + v, + r""" +set +e +echo '--- pb unit ---' +systemctl status douyinweb-pb --no-pager -l | head -35 +ls -la /opt/douyinWEB/pb/pocketbase 2>/dev/null +grep -E '8092|8090|PB' /etc/systemd/system/douyinweb-pb.service /etc/douyinweb.env 2>/dev/null | head +echo '--- who on 8090/8092 ---' +ss -lntp | grep -E ':(8090|8092)\b' +curl -sS -m 3 -o /dev/null -w '8090=%{http_code}\n' http://127.0.0.1:8090/ +curl -sS -m 3 -o /dev/null -w '8092=%{http_code}\n' http://127.0.0.1:8092/ +echo '--- neko containers all ---' +docker ps -a --format '{{.Names}} {{.Status}}' | grep -i neko | head -40 +echo '--- frp-aux tunnels ---' +systemctl status dy-frp-http-aux --no-pager -l | head -50 +ss -lntp | grep -E ':(18014|14015|28333|9999|920[0-7]|1820)\b' | head -40 +echo '--- dylive neko1 public ---' +curl -sS -m 8 -o /dev/null -w 'neko1=%{http_code}\n' https://dylive.nomadro.com/neko/1/ +curl -sS -m 8 -o /dev/null -w 'neko1_local=%{http_code}\n' http://127.0.0.1:9200/ +echo '--- wg latest-handshakes ---' +wg show wg-dy latest-handshakes +wg show wg-dy transfer +# check firewall for 51820 reply +iptables -L INPUT -n 2>/dev/null | grep -E '51820|wg' | head +nft list ruleset 2>/dev/null | grep -E '51820|wg-dy' | head +""", +) +v.close() + +p = ssh("107.173.30.245", 4014, "eric", "4669805") +print("===== PHYS PB binary / youtube =====", flush=True) +run( + p, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +ls -la /opt/douyinWEB/pb/ 2>/dev/null | head -20 +file /opt/douyinWEB/pb/pocketbase 2>/dev/null +which pocketbase 2>/dev/null +cat /etc/systemd/system/douyinweb-pb.service +echo "--- youtube service files ---" +ls /etc/systemd/system/douyinweb* 2>/dev/null +ps aux | grep -E "youtube|8020" | grep -v grep | head +echo "--- neko 9+ (should fail via wg) ---" +curl -sS -m 5 --noproxy "*" -o /dev/null -w "local9208=%{http_code}\n" http://127.0.0.1:9208/ || echo no9208 +ss -lntp | grep 9208 || echo no_listen_9208 +echo "--- iptables OUTPUT wg? ---" +iptables -L OUTPUT -n 2>/dev/null | head -20 +iptables -L INPUT -n 2>/dev/null | head -20 +# check if UDP 51820 from phys can reach and get reply - just show conntrack? +echo "--- home NAT public ---" +curl -sS -m 5 --noproxy "*" https://api.ipify.org; echo +' +""", +) +p.close() + +print("===== public neko higher ids =====", flush=True) +with httpx.Client(follow_redirects=False, timeout=12) as cl: + for base in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + for path in ("/neko/1/", "/neko/8/", "/neko/9/", "/ops-neko/1/", "/_/", "/shellcrash-ui"): + url = base + path + try: + r = cl.get(url) + print(f"{r.status_code} {url} loc={r.headers.get('location','')[:80]}", flush=True) + except Exception as ex: + print(f"ERR {url} {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_diag_dual_port_conflict.py b/scripts/_diag_dual_port_conflict.py new file mode 100644 index 0000000..c160a32 --- /dev/null +++ b/scripts/_diag_dual_port_conflict.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, banner_timeout=120, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=60): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +run( + v, + r""" +set +e +echo '--- VPS pb dir ---' +ls -la /opt/douyinWEB/pb/ | head -20 +file /opt/douyinWEB/pb/pocketbase /opt/douyinWEB/pb/pocketbase.exe 2>/dev/null +echo '--- who owns 9200 ---' +ss -lntp | grep ':9200' +# compare response identity: dylive neko vs dy neko title/cookies +echo '--- neko identity fingerprints ---' +curl -sS -m 8 http://127.0.0.1:9200/ | head -c 200; echo +curl -sS -m 8 -H 'Host: dylive.nomadro.com' http://127.0.0.1:9200/ | head -c 200; echo +# caddy routes for dylive neko1 +grep -A3 'handle_path /neko/1' /etc/caddy/sites/dylive.nomadro.com.caddy | head -10 +grep -A3 'handle_path /neko/1' /etc/caddy/sites/dy.nomadro.com.caddy | head -10 +echo '--- dylive ops-neko routes ---' +grep -nE 'ops-neko|1820' /etc/caddy/sites/dylive.nomadro.com.caddy | head -20 +echo '--- DY_PB_URL ---' +grep PB /etc/douyinweb.env +# pid 635 pocketbase cwd +pwdx 635 2>/dev/null; ls -l /proc/635/exe 2>/dev/null; tr '\0' ' ' < /proc/635/cmdline; echo +echo '--- nft masquerade context ---' +nft list ruleset 2>/dev/null | grep -n -B2 -A2 '10.8.0.2' | head -40 +""", +) +v.close() +print("DONE") diff --git a/scripts/_diag_dual_s3_covers.py b/scripts/_diag_dual_s3_covers.py new file mode 100644 index 0000000..9ea8766 --- /dev/null +++ b/scripts/_diag_dual_s3_covers.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Diagnose S3 / covers on dy + dylive. Read-only.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + +HOSTS = [ + ("dylive", "107.173.30.245", "https://dylive.nomadro.com"), + ("dy", "108.174.50.68", "https://dy.nomadro.live"), +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +SCRIPT = r""" +set +e +echo '=== units ===' +systemctl is-active douyinweb-api douyinweb-web 2>/dev/null +systemctl is-active seaweedfs-filer seaweed-filer weed-filer 2>/dev/null +systemctl list-units --type=service --all 2>/dev/null | grep -iE 'seaweed|weed|s3|minio' | head -20 +echo +echo '=== listen ports (s3/filer related) ===' +ss -lntp 2>/dev/null | grep -E ':8333|:8888|:18888|:8334|:9000|:9001|:8080|:8014|:4015' | head -30 +echo +echo '=== env / settings (S3 keys redacted) ===' +cd /opt/douyinWEB/backend 2>/dev/null || cd /opt/douyinWEB +if [ -f .venv/bin/python ]; then +./.venv/bin/python - <<'PY' +from app.config import settings +import os +keys = [ + 's3_endpoint','s3_public_endpoint','s3_bucket','s3_region','s3_access_key','s3_secret_key', + 'public_base_url','covers_dir','seaweed' +] +for k in dir(settings): + if any(x in k.lower() for x in ('s3','cover','public','seaweed','cdn')): + v = getattr(settings, k, None) + if k.lower().endswith('secret') or 'secret' in k.lower() or 'password' in k.lower() or 'key' in k.lower() and 'access' in k.lower(): + sv = str(v or '') + print(f'settings.{k}=', (sv[:4]+'***'+sv[-2:] if len(sv)>8 else ('***' if sv else ''))) + else: + print(f'settings.{k}=', v) +# env +for ek in sorted(os.environ): + if any(x in ek.upper() for x in ('S3','SEAWEED','COVER','PUBLIC_BASE','AWS','MINIO')): + val = os.environ[ek] + if any(x in ek.upper() for x in ('SECRET','PASSWORD','KEY')) and 'PUBLIC' not in ek.upper(): + print(f'env.{ek}=', (val[:4]+'***' if val else '')) + else: + print(f'env.{ek}=', val) +PY +fi +echo +echo '=== local covers dir ===' +ls -la /opt/douyinWEB/backend/data/covers 2>/dev/null | head -15 +find /opt/douyinWEB/backend/data/covers -type f 2>/dev/null | head -8 +echo count_files=$(find /opt/douyinWEB/backend/data/covers -type f 2>/dev/null | wc -l) +echo +echo '=== sample DB cover urls ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +try: + rows = db.list_sessions(limit=8) if hasattr(db,'list_sessions') else None +except Exception as e: + print('list_sessions err', e) + rows = None +# fallback raw sql +from app.db import _connect, _lock +with _lock: + conn=_connect() + try: + cur=conn.execute("SELECT id, cover_url, cover_proxy_url, anchor_name FROM sessions WHERE cover_url IS NOT NULL AND cover_url!='' ORDER BY started_at DESC LIMIT 8") + except Exception: + cur=conn.execute("SELECT id, cover_url, anchor_name FROM sessions WHERE cover_url IS NOT NULL AND cover_url!='' ORDER BY rowid DESC LIMIT 8") + for r in cur.fetchall(): + print(dict(r) if hasattr(r,'keys') else r) + try: + cur2=conn.execute("SELECT key, substr(value,1,120) FROM settings WHERE key LIKE '%s3%' OR key LIKE '%cover%' OR key LIKE '%public%' OR key LIKE '%seaweed%' LIMIT 30") + for r in cur2.fetchall(): + print('setting_row', r[0], r[1]) + except Exception as e: + print('settings_scan', e) +PY +echo +echo '=== local HTTP probes ===' +curl -sS -m 5 -o /dev/null -w 'api_health:%{http_code}\n' http://127.0.0.1:8014/api/health +# covers static +curl -sS -m 5 -o /dev/null -w 'covers_root:%{http_code}\n' http://127.0.0.1:8014/covers/ +curl -sS -m 5 -I http://127.0.0.1:8014/covers/ 2>&1 | head -15 +# seaweed filer +for p in 18888 8888 8333 8334; do + curl -sS -m 3 -o /dev/null -w "port_${p}:%{http_code}\n" http://127.0.0.1:$p/ || echo port_${p}:FAIL +done +echo HOST_DONE +""" + +for label, host, public in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + print(f"--- public probes {public} ---", flush=True) + for path in ("/api/health", "/covers/", "/"): + url = public + path + t0 = time.time() + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=15, context=CTX) as r: + print(path, r.status, f"t={time.time()-t0:.2f}s", "ct=", r.headers.get("content-type"), flush=True) + except Exception as ex: + print(path, "ERR", ex, f"t={time.time()-t0:.2f}s", flush=True) + +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_dual_s3_covers2.py b/scripts/_diag_dual_s3_covers2.py new file mode 100644 index 0000000..50b6b67 --- /dev/null +++ b/scripts/_diag_dual_s3_covers2.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Deeper cover/S3 probe: DB paths, public cover API, S3 bucket, env files.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + +HOSTS = [ + ("dylive", "107.173.30.245", "https://dylive.nomadro.com"), + ("dy", "108.174.50.68", "https://dy.nomadro.live"), +] + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +SCRIPT = r""" +set +e +cd /opt/douyinWEB/backend +echo '=== systemd env snippets ===' +for u in douyinweb-api; do + systemctl show "$u" -p Environment -p EnvironmentFiles 2>/dev/null | head -5 +done +ls /etc/systemd/system/douyinweb-api.service.d 2>/dev/null +grep -RniE 'S3_|PUBLIC_BASE|COVER|SEAWEED' /etc/systemd/system/douyinweb-api* /etc/default/douyinweb* /opt/douyinWEB/.env /opt/douyinWEB/backend/.env 2>/dev/null | head -40 +echo +echo '=== session_auth covers gate on disk ===' +grep -n 'covers' /opt/douyinWEB/backend/app/session_auth.py | head -20 +echo +echo '=== DB cover_path samples ===' +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + cols=[r[1] for r in conn.execute('PRAGMA table_info(sessions)').fetchall()] + print('sessions_cols_coverish=', [c for c in cols if 'cover' in c.lower() or c in ('id','anchor_name','status')]) + # count + try: + n=conn.execute("SELECT COUNT(*) FROM sessions WHERE cover_path IS NOT NULL AND cover_path!=''").fetchone()[0] + print('sessions_with_cover_path=', n) + except Exception as e: + print('count_err', e) + try: + rows=conn.execute("SELECT id, substr(cover_path,1,160), anchor_name FROM sessions WHERE cover_path IS NOT NULL AND cover_path!='' ORDER BY rowid DESC LIMIT 10").fetchall() + for r in rows: + print('sess', r[0][:8], r[1], r[2]) + except Exception as e: + print('rows_err', e) + # rooms avatar + try: + cols2=[r[1] for r in conn.execute('PRAGMA table_info(rooms)').fetchall()] + print('rooms_cols=', [c for c in cols2 if 'avatar' in c.lower() or 'cover' in c.lower() or c=='id']) + n2=conn.execute("SELECT COUNT(*) FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url!=''").fetchone()[0] + print('rooms_with_avatar=', n2) + for r in conn.execute("SELECT id, substr(avatar_url,1,160), name FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url!='' LIMIT 5").fetchall(): + print('room', r) + except Exception as e: + print('rooms_err', e) + # assign pool + try: + for r in conn.execute("SELECT id, substr(cover_url,1,160) FROM yt_assign_pool_urls WHERE cover_url IS NOT NULL AND cover_url!='' LIMIT 5").fetchall(): + print('pool', r) + except Exception as e: + print('pool_err', e) +PY +echo +echo '=== probe local cover file + APIs ===' +F=$(ls /opt/douyinWEB/backend/data/covers/*.jpg 2>/dev/null | head -1) +echo sample_file=$F +if [ -n "$F" ]; then + BN=$(basename "$F") + curl -sS -m 5 -o /dev/null -w "covers_file_noauth:%{http_code}\n" "http://127.0.0.1:8014/covers/$BN" +fi +# pick a session id with cover +SID=$(./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + r=conn.execute("SELECT id FROM sessions WHERE cover_path IS NOT NULL AND cover_path!='' ORDER BY rowid DESC LIMIT 1").fetchone() + print(r[0] if r else '') +PY +) +echo sid=$SID +if [ -n "$SID" ]; then + curl -sS -m 5 -o /dev/null -w "api_cover_noauth:%{http_code} size:%{size_download}\n" "http://127.0.0.1:8014/api/sessions/$SID/cover" + curl -sS -m 5 "http://127.0.0.1:8014/api/sessions/$SID/cover" | head -c 20 | xxd | head -2 +fi +echo +echo '=== S3 list bucket (boto-ish via app) ===' +./.venv/bin/python - <<'PY' +from app import s3_storage +from app.config import settings +print('s3_enabled_fn', s3_storage.s3_enabled()) +print('settings.s3_enabled', settings.s3_enabled) +# try force client even if disabled +try: + import boto3 + from botocore.client import Config + c=boto3.client('s3', endpoint_url=settings.s3_endpoint, aws_access_key_id=settings.s3_access_key, aws_secret_access_key=settings.s3_secret_key, region_name=settings.s3_region, config=Config(signature_version='s3v4')) + try: + c.head_bucket(Bucket=settings.s3_bucket) + print('head_bucket=OK') + except Exception as e: + print('head_bucket', type(e).__name__, e) + try: + r=c.list_objects_v2(Bucket=settings.s3_bucket, MaxKeys=5) + print('list_keys', [x['Key'] for x in r.get('Contents') or []]) + print('key_count_page', len(r.get('Contents') or []), 'is_truncated', r.get('IsTruncated')) + except Exception as e: + print('list_err', type(e).__name__, e) +except Exception as e: + print('boto_err', e) +PY +echo HOST_DONE +""" + +for label, host, public in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=150) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out, flush=True) + # extract a sample sid from output for public probe + sid = "" + for line in out.splitlines(): + if line.startswith("sid=") and len(line) > 4: + sid = line[4:].strip() + if line.startswith("sample_file=") and "/covers/" not in line: + pass + bn = "" + for line in out.splitlines(): + if line.startswith("sample_file=") and line.strip().endswith(".jpg"): + bn = line.split("/")[-1].strip() + print(f"--- public cover probes {public} ---", flush=True) + paths = [] + if bn: + paths.append(f"/covers/{bn}") + if sid: + paths.append(f"/api/sessions/{sid}/cover") + for path in paths or ["/covers/"]: + url = public + path + t0 = time.time() + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=20, context=CTX) as r: + data = r.read(64) + print(path, r.status, f"t={time.time()-t0:.2f}s", "bytes", len(data), "ct", r.headers.get("content-type"), flush=True) + except Exception as ex: + print(path, "ERR", ex, f"t={time.time()-t0:.2f}s", flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_dy_caddy_frp.py b/scripts/_diag_dy_caddy_frp.py new file mode 100644 index 0000000..bfbd425 --- /dev/null +++ b/scripts/_diag_dy_caddy_frp.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read current dy Caddy + FRP-aux (no edits).""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +cmd = r''' +set +e +echo '=== dy.caddy head/covers/neko1/frp ===' +# show first 120 lines of dy site +sed -n '1,120p' /etc/caddy/sites/dy.nomadro.com.caddy +echo '=== douyin-covers block ===' +grep -nA8 'douyin-covers' /etc/caddy/sites/dy.nomadro.com.caddy | head -40 +echo '=== frp aux unit ===' +systemctl cat dy-frp-http-aux 2>/dev/null | head -80 +echo '=== ss tunnels ===' +ss -lntp | grep -E '18014|14015|9999|920[0-7]|18333|18200|118200' || true +echo '=== ops-neko body sniff ===' +curl -sS -m 10 -D- -o /tmp/opsneko_body.html 'https://dy.nomadro.com/ops-neko/1' | head -30 +echo BODY_HEAD: +head -c 400 /tmp/opsneko_body.html; echo +echo '=== cover sample from physical via tunnel if any ===' +''' +_i,o,e=c.exec_command(cmd, timeout=60) +print((o.read()+e.read()).decode('utf-8','replace')) +c.close() diff --git a/scripts/_diag_dy_cover_urls.py b/scripts/_diag_dy_cover_urls.py new file mode 100644 index 0000000..ff9bbd2 --- /dev/null +++ b/scripts/_diag_dy_cover_urls.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Read-only: sample cover URLs after login on dy.nomadro.com. No config changes.""" +from __future__ import annotations + +import sys + +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +BASE = "https://dy.nomadro.com" +# known from earlier unit files in conversation history for this deploy +USER = "hackrobot" +PASS = "Xiao4669805@" + +with httpx.Client(follow_redirects=False, timeout=25) as cl: + r = cl.post(f"{BASE}/api/auth/login", json={"username": USER, "password": PASS}) + print("login", r.status_code, r.text[:120], flush=True) + token = "" + try: + token = (r.json() or {}).get("token") or (r.json() or {}).get("access_token") or "" + except Exception: + pass + # cookie jar may also work + headers = {"Authorization": f"Bearer {token}"} if token else {} + for path in ["/api/sessions?status=live", "/api/sessions?live=1", "/api/sessions"]: + rr = cl.get(f"{BASE}{path}", headers=headers) + print(f"\n{path} -> {rr.status_code}", flush=True) + if rr.status_code != 200: + print(rr.text[:200], flush=True) + continue + data = rr.json() + sessions = data.get("sessions") or data.get("items") or data if isinstance(data, list) else [] + if isinstance(data, dict) and not sessions: + # try nested + for k, v in data.items(): + if isinstance(v, list) and v: + sessions = v + print("using key", k, flush=True) + break + print("count", len(sessions) if isinstance(sessions, list) else type(sessions), flush=True) + n = 0 + for s in (sessions if isinstance(sessions, list) else [])[:8]: + if not isinstance(s, dict): + continue + if s.get("ended_at") and not s.get("live"): + # still show a few with covers + pass + urls = { + "avatar_url": s.get("avatar_url"), + "cover_url": s.get("cover_url"), + "cover_proxy_url": s.get("cover_proxy_url"), + "id": s.get("id"), + "anchor": s.get("anchor_name") or s.get("room_id"), + "ended": s.get("ended_at"), + } + print(urls, flush=True) + for label in ("avatar_url", "cover_url", "cover_proxy_url"): + u = urls.get(label) + if not u or not str(u).startswith("http"): + continue + try: + ir = cl.get(str(u), headers=headers if "dy.nomadro.com" in str(u) else None) + print(f" GET {label} -> {ir.status_code} ctype={ir.headers.get('content-type','')[:40]} len={len(ir.content)}", flush=True) + except Exception as ex: + print(f" GET {label} ERR {ex}", flush=True) + # also try api cover + sid = s.get("id") + if sid: + try: + ir = cl.get(f"{BASE}/api/sessions/{sid}/cover", headers=headers) + print(f" GET /api/sessions/{sid}/cover -> {ir.status_code} ctype={ir.headers.get('content-type','')[:40]}", flush=True) + except Exception as ex: + print(f" cover api ERR {ex}", flush=True) + n += 1 + if n >= 5: + break + if rr.status_code == 200: + break + + # public s3 host + for u in [ + "https://s3.nomadro.com/", + "https://dy.nomadro.com/covers/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_diag_dy_covers_caddy.py b/scripts/_diag_dy_covers_caddy.py new file mode 100644 index 0000000..6b1dd43 --- /dev/null +++ b/scripts/_diag_dy_covers_caddy.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Read-only: inspect /covers and /douyin-covers caddy blocks. No edits.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = r''' +sed -n '20,45p;500,520p' /etc/caddy/sites/dy.nomadro.com.caddy +echo '---' +# probe a known path pattern if any object exists via public +curl -sS -m 8 -o /dev/null -w 'douyin_covers_root=%{http_code}\n' https://dy.nomadro.com/douyin-covers/ +curl -sS -m 8 -o /dev/null -w 'covers_root=%{http_code}\n' https://dy.nomadro.com/covers/ +curl -sS -m 5 -o /dev/null -w 'via_wg_8333=%{http_code}\n' http://10.8.0.2:8333/ || true +''' +_i, o, e = c.exec_command(cmd, timeout=40) +while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) +sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) +sys.stdout.flush() +c.close() +print("DONE", flush=True) diff --git a/scripts/_diag_dy_cpu100.py b/scripts/_diag_dy_cpu100.py new file mode 100644 index 0000000..3f066e7 --- /dev/null +++ b/scripts/_diag_dy_cpu100.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Diagnose CPU 100% on dy.nomadro.live vs dylive — read-only.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [ + ("dy-live", "108.174.50.68"), + ("dylive", "107.173.30.245"), +] +PASS = "Xiao4669805" + +SCRIPT = r""" +set +e +echo '=== host ===' +hostname; nproc; free -h | head -2 +uptime +echo +echo '=== top cpu (snapshot) ===' +ps aux --sort=-%cpu | head -25 +echo +echo '=== load / steal ===' +mpstat 1 3 2>/dev/null || vmstat 1 3 +echo +echo '=== docker / neko ===' +docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.RunningFor}}' 2>/dev/null | head -40 +echo neko_count=$(docker ps -q --filter name=neko 2>/dev/null | wc -l) +echo +echo '=== chrome / ffmpeg counts ===' +echo chrome=$(pgrep -c chrome 2>/dev/null || pgrep -c chromium 2>/dev/null || echo 0) +echo ffmpeg=$(pgrep -c ffmpeg 2>/dev/null || echo 0) +echo node=$(pgrep -c node 2>/dev/null || echo 0) +echo python=$(pgrep -c python 2>/dev/null || echo 0) +echo npm=$(pgrep -af 'npm|next|node.*build' 2>/dev/null | grep -v grep | head -15) +echo +echo '=== systemd hot ===' +systemctl is-active douyinweb-api douyinweb-web douyinweb-s3 douyinweb-pb douyinweb-yt 2>/dev/null +systemctl status douyinweb-api --no-pager -l 2>&1 | head -20 +echo +echo '=== api threads / cpu ===' +PID=$(ss -lntp 2>/dev/null | awk '/:8014/ {match($0,/pid=[0-9]+/); if(RSTART){print substr($0,RSTART+4,RLENGTH-4); exit}}') +echo api_pid=$PID +if [ -n "$PID" ]; then + ps -p $PID -o pid,pcpu,pmem,rss,nlwp,etime,cmd + # children + ps --ppid $PID -o pid,pcpu,pmem,rss,cmd --sort=-pcpu 2>/dev/null | head -15 +fi +echo +echo '=== assign neko enabled ===' +cd /opt/douyinWEB/backend 2>/dev/null && ./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + rows=conn.execute('SELECT name, neko_instance_id, neko_enabled FROM yt_assign_groups ORDER BY neko_instance_id').fetchall() + en=0 + for r in rows: + print(dict(r) if hasattr(r,'keys') else r) + if r[2]: en+=1 + print('enabled_count', en, 'total', len(rows)) +PY +echo +echo '=== recent api log cpu-ish ===' +journalctl -u douyinweb-api -n 40 --no-pager 2>/dev/null | tail -40 +echo HOST_DONE +""" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print(f"retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh fail {host}") + + +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_dy_cpu_neko_orphan.py b/scripts/_diag_dy_cpu_neko_orphan.py new file mode 100644 index 0000000..2b4e109 --- /dev/null +++ b/scripts/_diag_dy_cpu_neko_orphan.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Check orphan Neko vs enabled flags; API CPU reason on dy.live.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", e, flush=True) + time.sleep(2) + raise SystemExit("fail") + + +c = connect("108.174.50.68") +_i, o, e = c.exec_command( + r""" +set +e +echo '=== neko container vs DB ===' +docker ps -a --filter name=neko --format '{{.Names}} {{.Status}}' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + rows=conn.execute('SELECT name, neko_instance_id, neko_enabled FROM yt_assign_groups WHERE neko_instance_id=10 OR neko_enabled=1').fetchall() + for r in rows: + print(dict(r)) +PY +echo +echo '=== ffmpeg threads / input ===' +ps -eo pid,pcpu,pmem,cmd | grep '[f]fmpeg' | head -5 +# how many cores ffmpeg uses +PID=$(pgrep -n ffmpeg) +if [ -n "$PID" ]; then + echo ffmpeg_pid=$PID + top -b -n 1 -H -p $PID 2>/dev/null | head -20 +fi +echo +echo '=== who polls API (last 3 min unique peers) ===' +journalctl -u douyinweb-api --since '3 min ago' --no-pager 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | sort | uniq -c | sort -rn | head +echo req_count=$(journalctl -u douyinweb-api --since '3 min ago' --no-pager 2>/dev/null | grep -c 'HTTP/1.1') +echo +echo '=== single path exclusive? ===' +./.venv/bin/python - <<'PY' +from app import db +try: + s=db.get_settings() if hasattr(db,'get_settings') else {} +except Exception as e: + s={} + print('settings_err', e) +# kv +from app.db import _connect, _lock +with _lock: + conn=_connect() + for k in ('relay_single_exclusive','single_path','host_profile','egress_mode','neko_exclusive'): + try: + r=conn.execute("SELECT key, substr(value,1,80) FROM settings WHERE key LIKE ?", ('%'+k+'%',)).fetchall() + for x in r: print('set', x) + except Exception: pass + try: + for r in conn.execute("SELECT key, substr(value,1,100) FROM settings WHERE key LIKE '%exclusive%' OR key LIKE '%host%' OR key LIKE '%neko%' LIMIT 30").fetchall(): + print(r) + except Exception as e: + print(e) +PY +echo +echo '=== cpu now ===' +uptime +mpstat 1 2 2>/dev/null | tail -5 +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_dy_docker.py b/scripts/_diag_dy_docker.py new file mode 100644 index 0000000..ed3d0e8 --- /dev/null +++ b/scripts/_diag_dy_docker.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmds = [ + 'docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"', + "pgrep -a ffmpeg | head -15; echo ffmpeg_count=$(pgrep -c ffmpeg || true)", + "docker ps -q --filter name=neko | wc -l; docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' 2>/dev/null | head -30", +] +for cmd in cmds: + print(f"\n===== {cmd[:80]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=60) + print(o.read().decode("utf-8", "replace"), end="", flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err, flush=True) +c.close() diff --git a/scripts/_diag_dy_false_live_nomadvlog.py b/scripts/_diag_dy_false_live_nomadvlog.py new file mode 100644 index 0000000..5251178 --- /dev/null +++ b/scripts/_diag_dy_false_live_nomadvlog.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Why dy shows nomad vlog as live when user says not live — read only.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "108.174.50.68" +PASS = "Xiao4669805" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + cmd = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import yt_assign_db, youtube_neko, youtube_live +from app import db + +# find nomad vlog groups +hits=[] +for g in yt_assign_db.list_groups(include_urls=True): + name=str(g.get('name') or '') + if 'nomad' in name.lower() and 'vlog' in name.lower(): + hits.append(g) + elif str(g.get('youtube_channel_id') or '').find('nomad')>=0: + hits.append(g) + +if not hits: + for g in yt_assign_db.list_groups(include_urls=False): + if int(g.get('neko_instance_id') or 0)==6: + hits.append(g) + +print('hits', len(hits)) +for g in hits: + gid=g.get('id') + ycid=str(g.get('youtube_channel_id') or g.get('channel_id') or '') + print('\n====', g.get('name'), gid, 'UC?', ycid) + print('neko', g.get('neko_instance_id'), 'enabled', g.get('neko_enabled'), 'category', g.get('category')) + # studio snap + snap=youtube_neko.studio_snapshot_for_group(g, max_age_sec=300) + print('STUDIO', json.dumps({k:snap.get(k) for k in [ + 'live_page_open','on_air','encoder_lost','session_live','live_status','viewer_count','health', + 'url','age_sec','detect_source','ui_source','preparing_stream']}, ensure_ascii=False)) + # relay state + try: + from app import youtube_relay_db + st=youtube_relay_db.get_relay_state(gid) or {} + print('RELAY', {k:st.get(k) for k in ('status','ffmpeg_pid','error','updated_at','is_pushing')}) + except Exception as e: + print('relay_err', e) + # ffmpeg for this? + +# public live probes +ids=[] +for g in hits: + for k in ('youtube_channel_id','channel_id'): + v=str(g.get(k) or '').strip() + if v.startswith('UC'): + ids.append(v) +ids=sorted(set(ids)) +print('\nUC ids', ids) +if ids: + try: + batch=youtube_live.batch_channel_live(ids) if hasattr(youtube_live,'batch_channel_live') else None + print('batch_fn', type(batch)) + except Exception as e: + print('batch_err', e) + # try common APIs + for fn_name in ['probe_channels_live','batch_is_live','youtubei_batch_live','fetch_live_map']: + fn=getattr(youtube_live, fn_name, None) + if callable(fn): + try: + r=fn(ids) + print(fn_name, json.dumps(r, ensure_ascii=False, default=str)[:1500]) + except Exception as e: + print(fn_name, 'ERR', e) + +# homepage / live-map style +try: + from app import main as app_main +except Exception: + pass + +# search code paths used by assign cards +import sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +print('\n=== relay states for neko6 groups ===') +for r in con.execute("SELECT group_id,status,ffmpeg_pid,error,updated_at FROM yt_relay_states ORDER BY updated_at DESC LIMIT 20"): + print(dict(r)) + +print('\n=== ffmpeg ===') +import subprocess +out=subprocess.check_output(['bash','-lc',"pgrep -a ffmpeg | head -5 || true"], text=True) +print(out) +PY + +# API endpoints the FE uses for card live badge +echo '=== openapi live paths ===' +curl -sS -m 10 http://127.0.0.1:8014/openapi.json | python3 -c "import sys,json; d=json.load(sys.stdin); print('\n'.join(sorted(p for p in d.get('paths',{}) if 'live' in p.lower() or 'assign' in p.lower())[:50]))" + +# login + fetch assign overview / live map if any +python3 - <<'PY' +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +print('login', op.open(req, timeout=20).read()[:80]) +for path in [ + '/api/youtube/assign/groups', + '/api/youtube/live/map', + '/api/youtube/assign/live-map', + '/api/ops/live-map', + '/api/youtube/relay/status', +]: + try: + r=op.open('http://127.0.0.1:8014'+path, timeout=30) + body=r.read().decode('utf-8','replace') + print('\nPATH', path, 'len', len(body)) + # find nomad + if 'nomad' in body.lower() or 'LIVE' in body: + # try parse + try: + d=json.loads(body) + except Exception: + print(body[:500]); continue + # walk for nomadvlog-ish + def walk(x, path=''): + if isinstance(x, dict): + name=str(x.get('name') or x.get('title') or '') + if 'nomad' in name.lower() and 'vlog' in name.lower(): + keys=['name','is_live','live','on_air','status','yt_live','channel_live','receiving','studio','neko'] + print('CARD', {k:x.get(k) for k in keys if k in x or True}) + print('FULL_KEYS', sorted(x.keys())[:60]) + # print live-related fields + for k,v in x.items(): + if any(t in k.lower() for t in ('live','air','receiv','push','status','studio','viewer')): + print(' ', k, '=', str(v)[:200]) + for k,v in x.items(): + walk(v, path+'.'+k) + elif isinstance(x, list): + for i,v in enumerate(x[:200]): + walk(v, path+f'[{i}]') + walk(d) + except Exception as e: + print('PATH', path, e) +PY +""" + _i, o, e = c.exec_command(cmd, timeout=120) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:2000], flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dy_images.py b/scripts/_diag_dy_images.py new file mode 100644 index 0000000..a68c12b --- /dev/null +++ b/scripts/_diag_dy_images.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Read-only: why images missing on dy.nomadro.com. No config changes.""" +from __future__ import annotations + +import re +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, port, user, pw, timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=50): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## public page + sample image URLs from API", flush=True) +with httpx.Client(follow_redirects=False, timeout=25) as cl: + # try common live/session endpoints + for u in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/api/sessions", + "https://dy.nomadro.com/api/live", + "https://dy.nomadro.com/api/rooms", + "https://dy.nomadro.com/api/dashboard", + "https://dy.nomadro.com/api/platform/dashboard", + "https://dy.nomadro.com/api/youtube/live-map", + ]: + try: + r = cl.get(u) + text = r.text[:500].replace("\n", " ") + print(f"{u} -> {r.status_code} {text[:180]}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("## caddy cover/s3 routes on VPS", flush=True) +v = connect(22) +run( + v, + "grep -nE 'cover|8333|s3\\.|/covers|nomdfs|Static' /etc/caddy/sites/dy.nomadro.com.caddy | head -40; " + "echo ---; " + "grep -nE 'reverse_proxy 10\\.8\\.0\\.2:8333|reverse_proxy 127\\.0\\.0\\.1:8333|s3.nomadro' /etc/caddy/sites/dy.nomadro.com.caddy | head -20; " + "ss -lntp | grep -E ':(8333|18014|14015)\\b' || true; " + "curl -sS -m 6 -o /dev/null -w 'local_s3=%{http_code}\\n' http://127.0.0.1:8333/ || true; " + "curl -sS -m 6 -o /dev/null -w 'wg_s3=%{http_code}\\n' http://10.8.0.2:8333/ || true; " + "curl -sS -m 6 -o /dev/null -w 'frp_api=%{http_code}\\n' http://127.0.0.1:18014/api/health", +) +v.close() + +print("## guest covers/s3", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "ss -lntp | grep 8333 || true; " + "curl -sS -m 5 http://127.0.0.1:8014/api/health | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get(\\\"s3\\\"))\"; " + "curl -sS -m 8 \"http://127.0.0.1:8014/api/sessions\" 2>/dev/null | head -c 400; echo; " + "curl -sS -m 8 \"http://127.0.0.1:8014/api/live\" 2>/dev/null | head -c 400; echo; " + "ls /opt/douyinWEB/backend/data/covers 2>/dev/null | head -5; " + "env | grep -E \"DY_S3|DY_PUBLIC\" 2>/dev/null | head -10; " + "systemctl show douyinweb-api -p Environment 2>/dev/null | tr \" \" \"\\n\" | grep -E \"DY_S3|DY_PUBLIC|DY_COVER\" | head -20" + "'", + t=50, +) +g.close() +print("DONE", flush=True) diff --git a/scripts/_diag_dy_live_map_nomad.py b/scripts/_diag_dy_live_map_nomad.py new file mode 100644 index 0000000..40ba801 --- /dev/null +++ b/scripts/_diag_dy_live_map_nomad.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Inspect live-map entries for nomad vlog channels on dy.""" +from __future__ import annotations + +import json +import sys +import urllib.request +import http.cookiejar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import asyncio, json +from app import youtube_live + +async def main(): + m = await youtube_live.build_live_map(force=True) + entries = m.get('entries') or {} + print('entry_count', len(entries), 'built_at', m.get('built_at') or m.get('updated_at')) + for k,v in entries.items(): + blob=json.dumps(v, ensure_ascii=False) + if 'nomad' in blob.lower() or 'UCtVf' in blob or 'UCO9w' in blob or 'e8154893' in blob or 'cbc11265' in blob: + print('\nKEY', k) + print(json.dumps(v, ensure_ascii=False, indent=2)[:1200]) + # also print all is_live true + print('\n=== ALL LIVE ===') + for k,v in entries.items(): + if v.get('is_live'): + print(k, 'src=', v.get('source'), 'title=', (v.get('title') or '')[:40], 'gid=', v.get('assign_group_id'), 'cid=', v.get('channel_id') or v.get('youtube_channel_id')) + +asyncio.run(main()) +PY +""" +_i,o,e=c.exec_command(cmd, timeout=180) +print(o.read().decode()) +print(e.read().decode()[:1500]) +c.close() diff --git a/scripts/_diag_dy_live_services.py b/scripts/_diag_dy_live_services.py new file mode 100644 index 0000000..13b3899 --- /dev/null +++ b/scripts/_diag_dy_live_services.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Read-only inventory of services on dy.nomadro.live.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "108.174.50.68" +PASS = "Xiao4669805" + + +def run(c, cmd, timeout=60): + print(f"\n===== {cmd[:90]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + out = o.read().decode("utf-8", "replace") + err = e.read().decode("utf-8", "replace") + if out: + sys.stdout.write(out) + if err and err.strip(): + sys.stdout.write("[stderr]\n" + err) + sys.stdout.flush() + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + print(f"ssh {HOST} try {i}...", flush=True) + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + print("ssh ok", flush=True) + break + except Exception as e: + print(f"fail: {e}", flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + run(c, "hostname; uptime; free -h; nproc; cat /etc/os-release | head -4") + run(c, "systemctl list-units --type=service --state=running --no-pager --no-legend | sort") + run( + c, + "systemctl list-unit-files --type=service --state=enabled --no-pager --no-legend 2>/dev/null | " + "awk '{print $1}' | sort | head -120", + ) + run( + c, + "for u in douyinweb-api douyinweb-web nginx caddy docker containerd " + "sing-box frpp 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' seaweedfs seaweed " + "redis redis-server postgresql mysql mongod; do " + "printf '%-28s %s\\n' \"$u\" \"$(systemctl is-active \"$u\" 2>/dev/null || echo n/a)\"; done", + ) + run( + c, + "ss -lntp 2>/dev/null | head -80 || netstat -lntp 2>/dev/null | head -80", + ) + run( + c, + "docker ps --format 'table {{.Names}}\\t{{.Status}}\\t{{.Ports}}' 2>/dev/null || echo 'no docker'", + ) + run( + c, + "ps aux --sort=-%cpu | head -25; echo '---MEM---'; ps aux --sort=-%mem | head -15", + ) + run( + c, + "systemctl list-units --type=service --state=failed --no-pager --no-legend || true; " + "echo '---'; ls /etc/systemd/system/*.service 2>/dev/null | xargs -n1 basename | sort", + ) + c.close() + print("\nDONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dy_neko6_cdp.py b/scripts/_diag_dy_neko6_cdp.py new file mode 100644 index 0000000..b58cd21 --- /dev/null +++ b/scripts/_diag_dy_neko6_cdp.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Why CDP scrape skips neko 6 on dy.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import youtube_neko, yt_assign_db +import json + +# list instances status +inst = youtube_neko.list_instances() if hasattr(youtube_neko,'list_instances') else None +print('list_instances type', type(inst)) +if isinstance(inst, list): + for x in inst: + if int(x.get('id') or 0) in (1,6) or x.get('running'): + print({k:x.get(k) for k in ('id','running','ready','enabled','status','name')}) +elif isinstance(inst, dict): + print(list(inst.keys())[:20]) + +# find scrape entrypoints +import inspect +names=[n for n in dir(youtube_neko) if 'scrape' in n.lower() or 'cdp' in n.lower() or 'telemetry' in n.lower()] +print('fns', names) + +# try scrape neko 6 now +if hasattr(youtube_neko, 'scrape_studio_via_cdp'): + r = youtube_neko.scrape_studio_via_cdp(6) + print('scrape6', json.dumps(r, ensure_ascii=False, default=str)[:1500]) +elif hasattr(youtube_neko, 'cdp_scrape_studio'): + r = youtube_neko.cdp_scrape_studio(6) + print('scrape6', json.dumps(r, ensure_ascii=False, default=str)[:1500]) + +# inspect how scrape targets chosen +src=open('app/youtube_neko.py',encoding='utf-8',errors='replace').read() +for needle in ['neko_enabled', 'cdp_studio_scrape', 'scrape_running', 'for nid', 'instance_ids']: + print('count', needle, src.count(needle)) +PY + +echo '=== manual cdp scrape script ===' +# find how cdp connects to neko 6 +grep -n '9222\|cdp\|neko' /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | head -40 +# docker exec scrape +docker exec douyinweb-neko-6 curl -sS -m 3 http://127.0.0.1:9222/json/version 2>/dev/null | head -c 300; echo +# run scrape from host against container? check compose for cdp publish +docker inspect douyinweb-neko-6 --format '{{range $p,$c := .NetworkSettings.Ports}}{{$p}} -> {{$c}}{{println}}{{end}}' | head -30 +ls /opt/douyinWEB/backend/data/neko/profiles/6/ 2>/dev/null | head +# extension instance id +docker exec douyinweb-neko-6 cat /etc/neko/live-ops-extension/instance_id.txt 2>/dev/null; echo +docker exec douyinweb-neko-6 ls /etc/neko/live-ops-extension/ 2>/dev/null | head +# recent api ingest logs +journalctl -u douyinweb-api --since '30 min ago' --no-pager | grep -iE 'studio|telemetry|neko.6|local:6|cdp' | tail -40 +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err.strip(): + print("[stderr]", err[:2000]) +c.close() diff --git a/scripts/_diag_dy_neko6_live_page.py b/scripts/_diag_dy_neko6_live_page.py new file mode 100644 index 0000000..3d19a18 --- /dev/null +++ b/scripts/_diag_dy_neko6_live_page.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Diagnose why local Neko Live page open but UI says closed — dy.nomadro.live only.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "108.174.50.68" +PASS = "Xiao4669805" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + cmd = r""" +set -e +echo '=== group nomadvlog ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import yt_assign_db, youtube_neko, yt_studio_db +from app import db + +groups = yt_assign_db.list_groups(include_urls=False) +hits = [g for g in groups if 'nomad' in str(g.get('name') or '').lower() or 'nomad' in str(g.get('brand') or '').lower()] +if not hits: + hits = [g for g in groups if int(g.get('neko_instance_id') or 0) == 6] +for g in hits or groups: + if int(g.get('neko_instance_id') or 0) not in (0,6) and 'nomad' not in str(g.get('name') or '').lower(): + continue + print('GROUP', g.get('id'), g.get('name'), 'neko', g.get('neko_instance_id'), 'enabled', g.get('neko_enabled'), + 'prefer', g.get('neko_open_prefer'), 'ops_slot', g.get('ops_neko_slot'), 'ops_url', (g.get('ops_neko_open_url') or '')[:60]) + snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=300.0) + print('SNAP', json.dumps({k:snap.get(k) for k in [ + 'live_page_open','on_air','live_status','viewer_count','total_views','url','age_sec','ui_source', + 'neko_kind','neko_ref','detect_source','received_at']}, ensure_ascii=False)) + nid = int(g.get('neko_instance_id') or 0) + if nid: + loc = youtube_neko.studio_snapshot_for_instance(nid, max_age_sec=300.0) + print('LOCAL', json.dumps({k:loc.get(k) for k in [ + 'live_page_open','on_air','live_status','viewer_count','url','age_sec','detect_source','received_at']}, ensure_ascii=False)) + print('---') + +# raw telemetry keys +print('=== telemetry refs ===') +youtube_neko._bootstrap_studio_telemetry_from_disk() +refs = sorted(getattr(youtube_neko, '_studio_latest_by_ref', {}).keys()) +print('refs', refs[:40], 'n=', len(refs)) +for key in list(refs): + if key in ('local:6','6', 'ops:6') or key.endswith(':6') or key == '6': + ev = youtube_neko._studio_latest_by_ref.get(key) + print('EV', key, json.dumps(ev, ensure_ascii=False, default=str)[:1200] if ev else None) +# also by neko id map +by = getattr(youtube_neko, '_studio_latest_by_neko', {}) +print('by_neko keys', sorted(by.keys())[:30]) +if 6 in by: + print('by_neko[6]', json.dumps(by[6], ensure_ascii=False, default=str)[:1200]) + +# recent studio samples in db +print('=== yt_studio recent for neko 6 ===') +try: + rows = yt_studio_db.list_recent_samples(neko_instance_id=6, limit=5) + for r in rows: + print({k:r.get(k) for k in ('neko_ref','live_page_open','on_air','viewer_count','url','received_at','neko_kind')}) +except Exception as e: + print('list_err', e) + import sqlite3 + con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') + con.row_factory=sqlite3.Row + for t in con.execute("SELECT name FROM sqlite_master WHERE name LIKE '%studio%'").fetchall(): + print('table', t[0]) + for r in con.execute("SELECT * FROM yt_studio_samples ORDER BY rowid DESC LIMIT 8").fetchall(): + d=dict(r) + for k,v in list(d.items()): + if isinstance(v,str) and len(v)>80: d[k]=v[:80]+'...' + print(d) +PY + +echo '=== docker neko 6 ===' +docker ps --filter name=neko-6 --format '{{.Names}} {{.Status}}' +echo '=== CDP tabs if possible ===' +# find cdp port for neko 6 +docker inspect douyinweb-neko-6 --format '{{json .NetworkSettings.Ports}}' 2>/dev/null | head -c 800; echo +# try curl chrome debug +for p in 9222 9226 9206; do + echo "port $p" + curl -sS -m 2 http://127.0.0.1:$p/json/list 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); +[print(x.get('url','')[:120], x.get('title','')[:40]) for x in d[:8]]" 2>/dev/null || true +done +# from container network +docker exec douyinweb-neko-6 curl -sS -m 3 http://127.0.0.1:9222/json/list 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); +[print(x.get('url','')[:140]) for x in d[:10]]" 2>/dev/null || echo 'no cdp in container' +""" + _i, o, e = c.exec_command(cmd, timeout=90) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:2000], flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dy_neko8_api_live.py b/scripts/_diag_dy_neko8_api_live.py new file mode 100644 index 0000000..27f6bfd --- /dev/null +++ b/scripts/_diag_dy_neko8_api_live.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Check live API relay status + ffmpeg for wisenomad (via running API, not fresh import).""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +set -e +echo "=== ffmpeg real ===" +ps -eo pid,etime,cmd | grep -E '[f]fmpeg' | head -20 || echo NONE +echo "=== api status snippet ===" +curl -sS -m 15 http://127.0.0.1:8014/api/youtube/relay/status | python3 -c ' +import sys,json +d=json.load(sys.stdin) +print("ok", d.get("ok"), "exclusive", d.get("exclusive_winner_group_id"), "running", d.get("running")) +for g in d.get("groups") or []: + if "8" in str(g.get("neko_instance_id")) or "wisenomad" in str(g.get("name") or "").lower() or g.get("group_id")=="23fb62dd-fd66-402b-983a-a4d8d09397af": + print("---", g.get("name"), g.get("group_id")) + for k in ("status","is_pushing","error","ffmpeg_pid","push_seconds","neko_instance_id","phase","pause_reason"): + print(f" {k}={g.get(k)}") + rl=g.get("recent_log") or [] + if isinstance(rl,str): rl=rl.splitlines() + print(" log_tail:") + for x in rl[-20:]: + print(" |", x) +' + +echo "=== studio snap via api if any ===" +curl -sS -m 10 "http://127.0.0.1:8014/api/youtube/neko/8/studio" 2>/dev/null | head -c 800 || true +echo +curl -sS -m 10 "http://127.0.0.1:8014/api/youtube/assign/groups/23fb62dd-fd66-402b-983a-a4d8d09397af" 2>/dev/null | python3 -c ' +import sys,json +try: + d=json.load(sys.stdin) +except Exception as e: + print("parse",e); sys.exit(0) +g=d.get("group") or d +print("group name", g.get("name"), "neko", g.get("neko_instance_id"), "neko_enabled", g.get("neko_enabled")) +' || true + +echo "=== journal last 5 min ffmpeg/relay kill ===" +journalctl -u douyinweb-api --since "5 min ago" --no-pager 2>/dev/null | grep -iE "invalid|NODATA|on_air|kill|stop|ffmpeg|waiting|blocked|wisenomad|1586410|green" | tail -40 || true +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command(REMOTE, timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dy_neko8_killloop.py b/scripts/_diag_dy_neko8_killloop.py new file mode 100644 index 0000000..5a899bf --- /dev/null +++ b/scripts/_diag_dy_neko8_killloop.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read relay DB + stream key + kill loop evidence on dy (no API auth).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +import json, time, sqlite3, os +from pathlib import Path +from app import db, yt_assign_db, youtube_relay_db, youtube_neko + +gid = "23fb62dd-fd66-402b-983a-a4d8d09397af" +g = yt_assign_db.get_group(gid) or {} +print("name", g.get("name")) +print("yt_channel", g.get("youtube_channel_id")) +print("stream_key_suffix", str(g.get("stream_key") or g.get("youtube_stream_key") or "")[-8:]) +# key fields vary +for k in sorted(g.keys()): + if "key" in k.lower() or "rtmp" in k.lower() or "stream" in k.lower(): + v = g.get(k) + if isinstance(v, str) and len(v) > 12: + print(f" field {k}=…{v[-12:]} len={len(v)}") + else: + print(f" field {k}={v}") + +st = youtube_relay_db.get_relay_state(gid) or {} +print("status", st.get("status"), "pid", st.get("ffmpeg_pid"), "err", (st.get("error") or "")[:240]) +print("started_at_age", round(time.time()-float(st.get("started_at") or 0),1) if st.get("started_at") else None) +logs = st.get("recent_log") or [] +if isinstance(logs, str): + logs = logs.splitlines() +print("=== FULL recent_log ===") +for x in logs: + print(x) + +snap = youtube_neko.studio_on_air_lookup(8, max_age_sec=30) +print("STUDIO", json.dumps({k:snap.get(k) for k in ("live_status","on_air","encoder_receiving","health","url","age_sec","viewer_count","detect_source")}, ensure_ascii=False)) + +# history table if any +conn = db.connect() +cur = conn.cursor() +for table in ("youtube_relay_state","relay_sessions","yt_relay_events","youtube_relay_log"): + try: + cur.execute(f"select name from sqlite_master where type='table' and name=?", (table,)) + if cur.fetchone(): + print("TABLE", table) + except Exception as e: + print("t", table, e) +try: + cur.execute("select id, group_id, status, reason, started_at, ended_at, substr(cast(metadata as text),1,120) from relay_sessions where group_id=? order by rowid desc limit 8", (gid,)) + rows = cur.fetchall() + print("relay_sessions rows", len(rows)) + for r in rows: + print(" ", r) +except Exception as e: + print("sessions_err", e) + # list columns + try: + cur.execute("pragma table_info(relay_sessions)") + print("cols", cur.fetchall()) + cur.execute("select * from relay_sessions where group_id=? order by rowid desc limit 3", (gid,)) + print(cur.fetchall()) + except Exception as e2: + print(e2) +conn.close() + +# ffmpeg alive? +import subprocess +out = subprocess.check_output(["bash","-lc","ps -eo pid,etime,cmd | grep -E '[f]fmpeg.*rtmps' | head -5"], text=True) +print("FFMPEG\n", out) +PY +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command(REMOTE, timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dy_neko8_relay_wait.py b/scripts/_diag_dy_neko8_relay_wait.py new file mode 100644 index 0000000..c14bb3c --- /dev/null +++ b/scripts/_diag_dy_neko8_relay_wait.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diag: why relay waits on Neko #8 Live page (dy).""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST, PASS = "108.174.50.68", "Xiao4669805" + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + HOST, 22, "root", PASS, timeout=40, + allow_agent=False, look_for_keys=False, banner_timeout=90, + ) + return c + except Exception as e: + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit("ssh_fail") + + +def run(c, cmd: str, t: int = 90) -> str: + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +REMOTE = r''' +set -e +echo "=== docker neko*8 ===" +docker ps -a --format '{{.Names}}\t{{.Status}}\t{{.Ports}}' | grep -i neko | grep -E '(^|[^0-9])8([^0-9]|$)|neko.?8' || true +docker ps -a --format '{{.Names}}\t{{.Status}}' | grep -i neko | sort +echo "=== unit api ===" +systemctl is-active douyinweb-api; systemctl show douyinweb-api -p ActiveState -p SubState --no-pager +echo "=== recent api lines ===" +journalctl -u douyinweb-api --since '30 min ago' --no-pager 2>/dev/null | grep -iE 'neko.?8|#8|抢跑|控制页|Live 页|ffmpeg|relay\]|studio|cdp|telemetry|ingest' | tail -60 +echo "=== python snap neko 8 ===" +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +from app import youtube_neko, yt_assign_db +from app.youtube_relay_pipeline import youtube_relay_pipeline +import json, time + +print("now", time.time()) +# groups on neko 8 +gs = [g for g in yt_assign_db.list_groups(include_urls=False) if int(g.get("neko_instance_id") or 0) == 8] +print("groups_neko8", len(gs)) +for g in gs: + print(" GROUP", g.get("id"), g.get("name"), "enabled", g.get("enabled"), "neko_enabled", g.get("neko_enabled"), + "prefer", g.get("neko_prefer"), "studio", str(g.get("neko_studio_url") or "")[:80]) + try: + snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=180.0, include_minute_reports=False) + except Exception as e: + snap = {"error": str(e)} + print(" SNAP", json.dumps({k: snap.get(k) for k in ( + "on_air","encoder_receiving","live_page_open","live_status","health","url","age_sec", + "received_at","detect_source","preparing_stream","encoder_lost","viewer_count","error" + ) if k in snap or snap.get(k) is not None}, ensure_ascii=False)[:500]) + +try: + local = youtube_neko.studio_on_air_lookup(8, max_age_sec=180.0) + print("LOCAL8", json.dumps(local, ensure_ascii=False)[:600]) +except Exception as e: + print("LOCAL8_ERR", e) + +# latest telemetry mentioning neko 8 / livestreaming +evs = youtube_neko.latest_studio_telemetry(limit=30) +print("telemetry_n", len(evs)) +for ev in evs[:12]: + p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + print(" EV", round(time.time()-float(ev.get("received_at") or 0),1), "s", + "neko", ev.get("neko_ref") or p.get("neko_ref") or p.get("instance_id"), + "st", p.get("live_status"), "url", str(p.get("url") or "")[:70]) + +st = youtube_relay_pipeline.status() +for r in st.get("groups") or []: + if int(r.get("neko_instance_id") or 0) == 8 or "8" in str(r.get("neko_label") or ""): + print("RELAY", json.dumps({k:r.get(k) for k in ( + "group_id","name","is_pushing","phase","last_error","neko_instance_id","pause_reason","detail" + )}, ensure_ascii=False)[:800]) + # dump more keys that look wait-related + keys = [k for k in r.keys() if any(x in k.lower() for x in ("wait","neko","studio","phase","push","log","msg"))] + print(" KEYS", keys) + for k in keys: + v = r.get(k) + if isinstance(v, (str, int, float, bool)) or v is None: + print(" ", k, "=", str(v)[:200]) +PY +''' + +c = connect() +print(run(c, REMOTE, t=120), flush=True) +c.close() diff --git a/scripts/_diag_dy_neko8_sigill_now.py b/scripts/_diag_dy_neko8_sigill_now.py new file mode 100644 index 0000000..6e4c18b --- /dev/null +++ b/scripts/_diag_dy_neko8_sigill_now.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose Neko #8 Chrome SIGILL on dy and apply known safe mitigations.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +HOST, PASS = "108.174.50.68", "Xiao4669805" +LOCAL_LAUNCH = ROOT / "backend" / "neko" / "browser-launch.sh" + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(HOST, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit("ssh_fail") + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +c = connect() +print("=== diagnose neko8 ===", flush=True) +print( + run( + c, + r""" +set +e +echo "-- container --" +docker ps -a --filter name=douyinweb-neko-8 --format '{{.Names}} {{.Status}}' +echo "-- chrome flags in container --" +docker exec douyinweb-neko-8 bash -lc 'head -n 5 /usr/local/bin/browser-launch.sh 2>/dev/null; grep -nE "SIGILL|OPENSSL|jitless|disable-gpu|memory-model|crash" /usr/local/bin/browser-launch.sh 2>/dev/null | head -40' +echo "-- recent chrome/neko logs --" +docker logs --tail 80 douyinweb-neko-8 2>&1 | grep -iE 'SIGILL|Aw, Snap|Illegal|chrome|FATAL|oom|killed' | tail -40 +echo "-- CDP --" +docker exec douyinweb-neko-8 bash -lc 'curl -fsS -m 2 http://127.0.0.1:9222/json/version 2>&1 | head -c 300; echo; curl -fsS -m 2 http://127.0.0.1:9222/json/list 2>&1 | head -c 400; echo' +echo "-- host cpu --" +lscpu | grep -E 'Model name|Flags|Vendor|Architecture' | head -10 +echo "-- mem --" +free -h | head -3 +""", + 90, + ), + flush=True, +) + +# Compare local vs container launch script for SIGILL mitigations +local = LOCAL_LAUNCH.read_text(encoding="utf-8", errors="replace") +print("local_has_jitless", "--jitless" in local or "jitless" in local, flush=True) +print("local_has_OPENSSL", "OPENSSL_ia32cap" in local, flush=True) + +c.close() diff --git a/scripts/_diag_dy_neko8_stick.py b/scripts/_diag_dy_neko8_stick.py new file mode 100644 index 0000000..63540a7 --- /dev/null +++ b/scripts/_diag_dy_neko8_stick.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Deeper dy neko8 relay stickiness: exclusive, wait hang, relay state.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +import json, time +from app import db, yt_assign_db, youtube_neko, youtube_relay_db +from app.youtube_relay_pipeline import youtube_relay_pipeline + +gid = "23fb62dd-fd66-402b-983a-a4d8d09397af" +cfg = db.get_settings_map() or {} +print("exclusive_live", cfg.get("youtube_relay_exclusive_live")) +print("auto_relay", cfg.get("youtube_relay_auto"), cfg.get("youtube_relay_enabled")) +print("on_air_deadline", cfg.get("youtube_relay_on_air_deadline_sec")) +print("pipeline_exclusive_winner", youtube_relay_pipeline._exclusive_winner) +print("neko_paused", getattr(youtube_relay_pipeline, "_neko_paused_instances", None)) + +st = youtube_relay_db.get_relay_state(gid) or {} +print("DB_STATE", json.dumps({k: st.get(k) for k in ( + "status","error","started_at","updated_at","ffmpeg_pid","source_url","anchor_name" +)}, ensure_ascii=False, default=str)) +logs = st.get("recent_log") or [] +if isinstance(logs, str): + print("LOG_STR", logs[-1500:]) +else: + print("LOG_N", len(logs)) + for line in (logs[-25:] if isinstance(logs, list) else []): + print(" ", line) + +# sessions in memory +sess = youtube_relay_pipeline._sessions.get(gid) +print("in_memory_session", bool(sess), "running", getattr(getattr(sess,"stats",None),"running",None) if sess else None) + +# test latest_live_studio_event filtering +now = time.time() +for since_delta in (0, 5, 30, 120): + ev = youtube_neko.latest_live_studio_event(max_age_sec=45.0, since_ts=now-since_delta, neko_id=8) + if ev: + p = ev.get("payload") or {} + print(f"EV since-{since_delta}s age={now-float(ev.get('received_at') or 0):.1f} st={p.get('live_status')} url={str(p.get('url') or '')[:60]} ref={ev.get('neko_ref')}") + else: + print(f"EV since-{since_delta}s NONE") + +# CDP signals +sig = youtube_neko._cdp_studio_page_signals(8, max_age_sec=0.0, force=True) +print("CDP_SIG", json.dumps({k:sig.get(k) for k in ( + "ok","control_ready","preparing_stream","live_status","on_air","live_page_open","url","error","reason" +) if k in sig}, ensure_ascii=False)[:800]) + +# full status row from API-like status +for r in (youtube_relay_pipeline.status().get("groups") or []): + if r.get("group_id")==gid: + print("STATUS_ROW status=", r.get("status"), "error=", (r.get("error") or "")[:200]) + print("is_pushing", r.get("is_pushing"), "waiting?", "waiting" in str(r.get("status") or "").lower()) + rl = r.get("recent_log") or [] + if isinstance(rl, list): + print("LAST_LOGS:") + for x in rl[-15:]: + print(" |", x) + break +PY + +echo "=== journal relay lines 20min ===" +journalctl -u douyinweb-api --since '20 min ago' --no-pager 2>/dev/null | grep -iE 'wisenomad|23fb62dd|neko wait|blocked|控制页|starting ffmpeg|ffmpeg|exclusive|Live 页' | tail -50 + +echo "=== ffmpeg processes ===" +ps aux | grep -E '[f]fmpeg' | head -20 || true +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command(REMOTE, timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dy_neko8_wait_once.py b/scripts/_diag_dy_neko8_wait_once.py new file mode 100644 index 0000000..f1d67e0 --- /dev/null +++ b/scripts/_diag_dy_neko8_wait_once.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe wait_group_ready_for_live for wisenomad / neko8 on dy.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +from app import yt_assign_db, youtube_neko +import json, time +g = yt_assign_db.get_group("23fb62dd-fd66-402b-983a-a4d8d09397af") +print("group", g.get("name"), "neko", g.get("neko_instance_id"), "neko_enabled", g.get("neko_enabled"), + "prefer", g.get("neko_open_prefer"), "ops", g.get("ops_neko_open_url"), "studio_url", g.get("neko_studio_url")) +print("--- wait once (timeout 8, settle 5, strict True) ---") +t0 = time.time() +r = youtube_neko.wait_group_ready_for_live(g, timeout_sec=8.0, settle_sec=5.0, strict=True) +print("elapsed", round(time.time()-t0,1)) +print(json.dumps(r, ensure_ascii=False, default=str)[:2000]) +print("--- evaluate page open helpers ---") +snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=60) +print("snap", json.dumps(snap, ensure_ascii=False, default=str)[:1200]) +# peek internal readiness if exposed +for name in ("_live_studio_page_open", "_payload_live_studio", "live_studio_ready", "_is_live_control_page"): + fn = getattr(youtube_neko, name, None) + print("fn", name, bool(fn)) +PY +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command(REMOTE, timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dy_site_pressure.py b/scripts/_diag_dy_site_pressure.py new file mode 100644 index 0000000..3d0311c --- /dev/null +++ b/scripts/_diag_dy_site_pressure.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Diagnose dy.nomadro.live pressure / hang. No config changes.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh_fail") + + +c = connect() +_i, o, e = c.exec_command( + r""" +set +e +echo '=== host ===' +hostname; uptime; free -m | head -2 +echo +echo '=== load / iowait ===' +vmstat 1 3 +echo +echo '=== top cpu/mem ===' +ps aux --sort=-%cpu | head -12 +echo '---' +ps aux --sort=-%mem | head -12 +echo +echo '=== app units ===' +systemctl is-active douyinweb-api douyinweb-web +ps -o pid,stat,etime,%cpu,%mem,cmd -C python,uvicorn,node,next-server 2>/dev/null | head -20 +pgrep -af 'uvicorn app.main|next-server' | head -10 +echo +echo '=== ports ===' +ss -lntp | grep -E ':8014|:4015|:443' || true +echo +echo '=== local latency ===' +for i in 1 2 3; do + curl -sS -m 8 -o /dev/null -w "health_$i:%{http_code} t=%{time_total}\n" http://127.0.0.1:8014/api/health || echo health_$i:FAIL + curl -sS -m 12 -o /dev/null -w "home_$i:%{http_code} t=%{time_total}\n" http://127.0.0.1:4015/ || echo home_$i:FAIL +done +echo +echo '=== neko ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}' "$n" +done +echo +echo '=== disk ===' +df -h / /opt 2>/dev/null | head -5 +echo +echo '=== api journal (errors) ===' +journalctl -u douyinweb-api -n 30 --no-pager 2>/dev/null | tail -30 +echo +echo '=== relay settings ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db, yt_assign_db +cfg=db.get_settings_map() +print('relay', cfg.get('youtube_relay_enabled'), 'slot', cfg.get('youtube_relay_time_slot_mode'), 'excl', cfg.get('youtube_relay_exclusive_live')) +en=[(g.get('name'), g.get('neko_instance_id'), g.get('neko_enabled')) for g in yt_assign_db.list_groups(include_urls=False, include_secret=False) if g.get('neko_enabled')] +print('neko_enabled', en) +PY +echo DY_DIAG_DONE +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +c.close() + +print("\n=== public probe ===", flush=True) +jar = CookieJar() +opener = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(jar), + urllib.request.HTTPSHandler(context=CTX), +) +t0 = time.time() +try: + with opener.open(urllib.request.Request("https://dy.nomadro.live/", method="GET"), timeout=25) as r: + body = r.read(2000) + print("home", r.status, f"t={time.time()-t0:.2f}s", "bytes", len(body), flush=True) +except Exception as e: + print("home ERR", e, f"t={time.time()-t0:.2f}s", flush=True) + +t0 = time.time() +try: + with opener.open(urllib.request.Request("https://dy.nomadro.live/api/health"), timeout=20) as r: + print("health", r.status, f"t={time.time()-t0:.2f}s", r.read(200), flush=True) +except Exception as e: + print("health ERR", e, f"t={time.time()-t0:.2f}s", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_diag_dylive_all_neko_tm.py b/scripts/_diag_dylive_all_neko_tm.py new file mode 100644 index 0000000..c2c6186 --- /dev/null +++ b/scripts/_diag_dylive_all_neko_tm.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Diagnose ALL dylive neko containers: Up/Created, chrome, Tampermonkey, CDP.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '======== ALL neko containers ========' +docker ps -a --filter name=douyinweb-neko --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | sort + +echo +echo '======== Caddy /neko routes sample ========' +grep -nE 'handle_path /neko/|reverse_proxy.*92' /etc/caddy/sites/*dylive* 2>/dev/null | head -40 +ls /etc/caddy/sites/ 2>/dev/null | head + +echo +echo '======== per-instance deep ========' +for name in $(docker ps -a --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + echo + echo "----- $name -----" + st=$(docker inspect -f '{{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}}' "$name" 2>/dev/null) + echo "state: $st" + # only exec if running + if docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null | grep -q true; then + docker exec "$name" sh -c ' +echo "supervisor:" +supervisorctl status 2>/dev/null | head -10 +echo "chrome_cdp:" +curl -sS -m 2 http://127.0.0.1:9222/json/version 2>/dev/null | head -c 120; echo +echo "tampermonkey_ext:" +ls -d /home/neko/.config/google-chrome/*/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo 2>/dev/null | head -5 +ls /home/neko/.config/google-chrome/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo 2>/dev/null | head -5 +# Preferences LoadExtension / disable +python3 - <<"PY" +import json,os,glob +prefs=glob.glob("/home/neko/.config/google-chrome/*/Preferences")+glob.glob("/home/neko/.config/google-chrome/Default/Preferences") +for p in prefs[:3]: + try: + d=json.load(open(p,encoding="utf-8")) + except Exception as e: + print("prefs_err",p,e); continue + ext=(d.get("extensions") or {}) + settings=ext.get("settings") or {} + tm=[k for k in settings if "dhdgffkkebhmkfjojejmpbldmpobfkfo" in k or k.startswith("dhdg")] + print("prefs",p,"tm_keys",tm[:3] or "NONE") + for k in list(settings.keys()): + if "dhdgff" in k or "tamper" in k.lower(): + s=settings[k] + print(" ",k,"state",s.get("state"),"path",str(s.get("path") or "")[:60],"manifest",bool(s.get("manifest"))) + # also check disable list + cmd=str((d.get("browser") or {}).get("enabled_labs_experiments") or "") +PY +echo "chrome_cmdline_ext:" +for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) + echo "$cmd" | tr " " "\n" | grep -iE "load-extension|disable-extensions|jitless|user-dir" | head -20 + break + ;; + esac +done +echo "tm_seed_mount:" +ls -la /etc/neko/tampermonkey-seed 2>/dev/null | head -5 +ls /opt 2>/dev/null | head -1 +' 2>&1 | head -80 + else + echo "(not running — skip exec)" + # show mounts / create reason + docker inspect -f 'Created={{.Created}} Image={{.Config.Image}}' "$name" 2>/dev/null + fi +done + +echo +echo '======== assign map neko ids ========' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + print(f"{g.get('name')[:24]:24} neko={g.get('neko_instance_id')} en={g.get('neko_enabled')} cat={g.get('category')}") +PY + +echo +echo '======== public neko/2 probe ========' +curl -sS -m 8 -o /dev/null -w 'neko2:%{http_code} redir=%{redirect_url}\n' https://dylive.nomadro.com/neko/2/ || echo fail +curl -sS -m 5 -o /dev/null -w 'local9201:%{http_code}\n' http://127.0.0.1:9201/ || echo local_fail +ss -lntp | grep -E ':920[0-9]|:921[0-9]' | head -30 + +echo +echo '======== mem ========' +free -h | head -2 +docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.CPUPerc}}' 2>/dev/null | grep neko | head -20 +""", + timeout=300, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_diag_dylive_autorelay.py b/scripts/_diag_dylive_autorelay.py new file mode 100644 index 0000000..fbee741 --- /dev/null +++ b/scripts/_diag_dylive_autorelay.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Check dylive (VPS hub) auto-relay + nomadvlog session — matches assign UI.""" +import json +import sys +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CREDS = [("hackrobot", "Xiao4669805@"), ("hackrobot", "Xiao4669805@!"), ("admin", "Xiao4669805@")] +BASE = "https://dylive.nomadro.com" + + +def main() -> None: + c = None + for u, p in CREDS: + c = httpx.Client(base_url=BASE, timeout=45, follow_redirects=True) + r = c.post("/api/auth/login", json={"username": u, "password": p}) + if r.status_code < 400: + print("login", u, "ok") + break + c.close() + c = None + if not c: + raise SystemExit("login fail") + + st = c.get("/api/youtube/relay/status").json() + s = st.get("settings") or {} + print("\n=== MASTER SWITCHES ===") + print("youtube_relay_enabled (自动推流):", s.get("youtube_relay_enabled")) + print("exclusive_live:", s.get("youtube_relay_exclusive_live")) + print("time_slot_mode (legacy):", s.get("youtube_relay_time_slot_mode")) + print("quality:", s.get("youtube_relay_quality_preset")) + print("pushing_count:", st.get("pushing_count"), "running:", st.get("running")) + print("exclusive_winner:", st.get("exclusive_winner_group_id")) + print("schedule:", json.dumps(st.get("schedule"), ensure_ascii=False)[:500]) + + groups = c.get("/api/youtube/assign/groups").json() + glist = groups.get("groups") if isinstance(groups, dict) else groups + print("\n=== GROUPS ===", len(glist or [])) + for g in glist or []: + title = g.get("youtube_title") or g.get("name") or "" + if "nomad" in title.lower() or "asian" in title.lower() or g.get("category") == "time_slot" or g.get("ops_neko_slot"): + print( + json.dumps( + { + "id": g.get("id"), + "title": title, + "cat": g.get("category"), + "enabled": g.get("enabled"), + "key": bool(str(g.get("stream_key") or "").strip() or g.get("has_stream_key")), + "prefer": g.get("neko_open_prefer"), + "ops_slot": g.get("ops_neko_slot"), + "ops_url": (g.get("ops_neko_open_url") or "")[:70], + "neko": g.get("neko_instance_id"), + "neko_en": g.get("neko_enabled"), + "featured_n": len(g.get("featured") or []), + "slot_n": len(g.get("slot_urls") or g.get("time_slot_urls") or []), + }, + ensure_ascii=False, + ) + ) + + print("\n=== PER-GROUP RELAY STATUS ===") + for g in st.get("groups") or []: + # find matching titles from assign + gid = g.get("group_id") or g.get("id") + print( + json.dumps( + { + "id": gid, + "title": g.get("youtube_title") or g.get("title") or g.get("name"), + "status": g.get("status") or g.get("state"), + "phase": g.get("phase"), + "message": (g.get("message") or g.get("wait_reason") or g.get("last_error") or "")[:120], + "source_url": (g.get("source_url") or g.get("douyin_url") or "")[:80], + "source_live": g.get("source_live") or g.get("dy_live"), + "ffmpeg_pid": g.get("ffmpeg_pid") or g.get("pid"), + "manual_hold": g.get("manual_hold"), + "in_schedule": g.get("in_schedule"), + "category": g.get("category"), + "studio": { + "live_page": (g.get("studio") or {}).get("live_page_open") + if isinstance(g.get("studio"), dict) + else g.get("studio_live_page"), + "ui_source": (g.get("studio") or {}).get("ui_source") + if isinstance(g.get("studio"), dict) + else None, + }, + }, + ensure_ascii=False, + ) + ) + + # probe the douyin room from user paste + room = "369511597884" + print("\n=== PROBE DOUYIN", room, "===") + for path in (f"/api/rooms/{room}", f"/api/douyin/probe?url=https://live.douyin.com/{room}", "/api/rooms"): + try: + r = c.get(path) + print(path, r.status_code, r.text[:400].replace("\n", " ")) + except Exception as e: + print(path, e) + + cat = c.get("/api/ops/neko/remote-catalog").json() + print("\n=== REMOTE CATALOG ===") + print(json.dumps(cat, ensure_ascii=False)[:1200]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_caddy_neko8.py b/scripts/_diag_dylive_caddy_neko8.py new file mode 100644 index 0000000..b42962c --- /dev/null +++ b/scripts/_diag_dylive_caddy_neko8.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + _i, o, e = c.exec_command( + "grep -nE 'neko/[0-9]|920[0-9]' /etc/caddy/sites/dylive.nomadro.com.caddy | head -60; " + "echo '---'; " + "docker inspect douyinweb-neko-8 --format 'HTTP={{(index (index .HostConfig.PortBindings \"8080/tcp\") 0).HostPort}}' 2>/dev/null; " + "docker inspect douyinweb-neko-8 --format '{{range $p,$c := .HostConfig.PortBindings}}{{$p}}->{{(index $c 0).HostPort}} {{end}}' | tr ' ' '\\n' | grep 8080", + timeout=30, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_neko12_sigill.py b/scripts/_diag_dylive_neko12_sigill.py new file mode 100644 index 0000000..063fed9 --- /dev/null +++ b/scripts/_diag_dylive_neko12_sigill.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Diagnose dylive neko/12 Chrome SIGILL Aw Snap; soft-recover Studio tab.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + print(f"\n===== {cmd[:100].replace(chr(10),' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return o.channel.recv_exit_status(), out + + +c = ssh() + +run( + c, + r""" +set +e +echo '=== host mem/cpu ===' +free -h | head -4 +nproc +lscpu | egrep 'Model name|Flags|Architecture|CPU\(s\)|Vendor' | head -20 +grep -E 'avx|sse4|avx2|amx' /proc/cpuinfo | head -1 | tr ' ' '\n' | grep -E '^(avx|avx2|sse4|ssse3|amx)' | sort -u +echo '=== neko12 container ===' +docker ps -a --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}} {{.Image}}' +docker inspect douyinweb-neko-12 --format 'MemLimit={{.HostConfig.Memory}} NanoCPUs={{.HostConfig.NanoCpus}} OomKillDisable={{.HostConfig.OomKillDisable}}' +echo '=== dmesg recent kill/ill ===' +dmesg -T 2>/dev/null | grep -iE 'neko-12|chrome|SIGILL|Out of memory|oom-kill|killed process' | tail -30 +journalctl -k -n 80 --no-pager 2>/dev/null | grep -iE 'oom|chrome|SIGILL|neko' | tail -20 +echo '=== inside neko12 ===' +docker exec douyinweb-neko-12 sh -c ' +set +e +echo CPU_IN_CTR: +grep -m1 flags /proc/cpuinfo | tr " " "\n" | grep -E "^(avx|avx2|sse4_2|ssse3)$" | sort -u +echo MEM: +free -h 2>/dev/null | head -3 || cat /proc/meminfo | head -5 +echo CHROME: +ps aux 2>/dev/null | grep -E "chrome|chromium" | grep -v grep | head -15 +echo FLAGS: +tr "\0" " " < /proc/$(pgrep -f "google-chrome.*remote-debugging" | head -1)/cmdline 2>/dev/null | head -c 800; echo +echo CRASHES: +ls -lt /home/neko/.config/google-chrome/Crash\ Reports/pending 2>/dev/null | head -5 +ls -lt /home/neko/.config/google-chrome/Crashpad/completed 2>/dev/null | head -5 +echo SUPERVISOR: +supervisorctl status 2>/dev/null || true +' +echo '=== other nekos health ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +""", + t=90, +) + +c.close() +print("DIAG_DONE") diff --git a/scripts/_diag_dylive_neko2_tm_scripts.py b/scripts/_diag_dylive_neko2_tm_scripts.py new file mode 100644 index 0000000..19bbae1 --- /dev/null +++ b/scripts/_diag_dylive_neko2_tm_scripts.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Deep-check dylive neko-2 Tampermonkey userscripts + chrome flags; compare neko-19.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) + +_i, o, e = c.exec_command( + r""" +set +e +for name in douyinweb-neko-2 douyinweb-neko-19; do + echo "======== $name ========" + docker exec "$name" sh -c ' +echo "--- volumes/profile size ---" +du -sh /home/neko/.config/google-chrome 2>/dev/null +du -sh /home/neko/.config/google-chrome/Default 2>/dev/null +echo "--- TM Local Extension Settings / LevelDB ---" +find /home/neko/.config/google-chrome -iname "*tamper*" 2>/dev/null | head -30 +find /home/neko/.config/google-chrome/Default -type d -name "IndexedDB" 2>/dev/null | head +ls -la /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo 2>/dev/null | head +ls -la /home/neko/.config/google-chrome/Default/IndexedDB/ 2>/dev/null | head -20 +# count script-ish files +find /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo -type f 2>/dev/null | wc -l +echo "--- provisioning log ---" +tail -40 /var/log/neko/tampermonkey-provisioning.log 2>/dev/null +echo "--- chrome flags (strings) ---" +tr "\0" "\n" < /proc/$(pgrep -n chrome | head -1)/cmdline 2>/dev/null | head -5 +for p in /proc/[0-9]*; do + if tr "\0" " " < "$p/cmdline" 2>/dev/null | grep -q "remote-debugging-port=9222"; then + tr "\0" "\n" < "$p/cmdline" | grep -iE "extension|disable|user-data|jitless|load-ext" + break + fi +done +echo "--- CDP tabs ---" +python3 - <<"PY" +import json,urllib.request +try: + tabs=json.load(urllib.request.urlopen("http://127.0.0.1:9222/json",timeout=5)) + print("tabs",len(tabs)) + for t in tabs[:8]: + print(t.get("type"), (t.get("url") or "")[:100], "|", (t.get("title") or "")[:40]) +except Exception as e: + print("cdp_err",e) +PY +echo "--- seed scripts? ---" +find /etc/neko/tampermonkey-seed -type f 2>/dev/null | head -40 +ls /etc/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo 2>/dev/null | head +' + echo "mounts TM:" + docker inspect "$name" --format '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}' | grep -iE 'tamper|chrome|profile|neko' | head -20 +done + +echo +echo '======== host seed scripts ========' +find /opt/douyinWEB/backend/neko/tampermonkey-seed -type f 2>/dev/null | head -40 +ls -la /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo 2>/dev/null | head +# look for .user.js +find /opt/douyinWEB/backend/neko -name "*.user.js" 2>/dev/null | head +find /opt/douyinWEB -name "*tampermonkey*" -type d 2>/dev/null | head + +echo +echo '======== neko-2 create time vs volume ========' +docker inspect douyinweb-neko-2 --format 'Created={{.Created}} Started={{.State.StartedAt}}' +docker inspect douyinweb-neko-2 --format '{{json .Mounts}}' | python3 -m json.tool 2>/dev/null | head -80 +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dylive_neko5_oom.py b/scripts/_diag_dylive_neko5_oom.py new file mode 100644 index 0000000..66b2435 --- /dev/null +++ b/scripts/_diag_dylive_neko5_oom.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Diagnose dylive neko-5 OOM + Chrome YouTube Live memory.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) +else: + raise SystemExit("ssh_fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== host mem / oom ===' +free -m | head -2 +uptime +dmesg -T 2>/dev/null | grep -iE 'Out of memory|Kill process|oom-kill|chrome' | tail -30 +journalctl -k --since '2 hours ago' 2>/dev/null | grep -iE 'Out of memory|Killed process|oom' | tail -20 + +echo +echo '=== neko fleet ===' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +echo +echo '=== container memstats (running) ===' +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort -V); do + docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}} lim={{.MemPerc}}' "$n" 2>/dev/null +done + +echo +echo '=== neko-5 detail ===' +docker inspect douyinweb-neko-5 --format 'State={{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Started={{.State.StartedAt}} Finished={{.State.FinishedAt}} Memory={{.HostConfig.Memory}} MemorySwap={{.HostConfig.MemorySwap}} NanoCPUs={{.HostConfig.NanoCpus}}' 2>&1 +docker inspect douyinweb-neko-5 --format '{{range .Mounts}}{{println .Source "->" .Destination}}{{end}}' 2>&1 | head -20 + +echo +echo '=== assign mapping 5 ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db, db +cfg=db.get_settings_map() +print('auto', cfg.get('youtube_relay_enabled'), 'slot', cfg.get('youtube_relay_time_slot_mode'), 'excl', cfg.get('youtube_relay_exclusive_live')) +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if int(g.get('neko_instance_id') or 0) == 5: + print({k:g.get(k) for k in ('name','neko_enabled','enabled','category','has_stream_key')}) +PY + +echo +echo '=== if up: chrome procs + tabs ===' +if docker ps --format '{{.Names}}' | grep -qx douyinweb-neko-5; then + docker exec douyinweb-neko-5 supervisorctl status 2>&1 + docker exec douyinweb-neko-5 sh -c 'curl -sS -m 3 http://127.0.0.1:9222/json/list 2>/dev/null' | head -c 4000; echo + docker exec douyinweb-neko-5 sh -c 'curl -sS -m 3 http://127.0.0.1:9222/json/version 2>/dev/null' | head -c 300; echo + # rss of chrome via /proc + docker exec douyinweb-neko-5 sh -c ' + tot=0 + for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null || true) + case "$cmd" in *chrome*|*Chrome*) + rss=$(awk "/VmRSS:/{print \$2}" "$p/status" 2>/dev/null) + [ -n "$rss" ] || continue + tot=$((tot+rss)) + echo "pid=${p##*/} rss_kb=$rss cmd=$(echo "$cmd" | cut -c1-120)" + ;; esac + done + echo TOTAL_CHROME_RSS_KB=$tot + ' 2>&1 | tail -40 + docker exec douyinweb-neko-5 sh -c 'grep -nE "max-old-space|jitless|renderer-process|js-flags|disable-features" /etc/neko/browser-launch.sh | head -20' + docker exec douyinweb-neko-5 sh -c 'tail -40 /var/log/neko/google-chrome.log 2>/dev/null' +else + echo neko-5_not_running + docker logs --tail 60 douyinweb-neko-5 2>&1 | tail -60 +fi + +echo +echo '=== host browser-launch flags ===' +grep -nE 'max-old-space|jitless|renderer-process|process-per-site|disable-features|PassageEmbeddings|WebAssembly' /opt/douyinWEB/backend/neko/browser-launch.sh | head -30 +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dylive_neko6_black.py b/scripts/_diag_dylive_neko6_black.py new file mode 100644 index 0000000..3cf628d --- /dev/null +++ b/scripts/_diag_dylive_neko6_black.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Diagnose dylive neko-6 black screen. Never recreate Neko.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + break + except Exception as e: + print("ssh_retry", i, e, flush=True) + time.sleep(2 + i) +else: + raise SystemExit("ssh_fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== mem / load ===' +free -m | head -2 +uptime +echo +echo '=== all neko ===' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +echo +echo '=== neko-6 inspect ===' +docker inspect douyinweb-neko-6 --format 'State={{.State.Status}} Health={{if .State.Health}}{{.State.Health.Status}}{{else}}n/a{{end}} Started={{.State.StartedAt}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}}' 2>&1 +echo +echo '=== supervisor inside neko-6 ===' +docker exec douyinweb-neko-6 supervisorctl status 2>&1 | head -40 +echo +echo '=== chrome / x processes ===' +docker exec douyinweb-neko-6 bash -lc 'ps auxww | egrep -i "chrome|openbox|xorg|neko|pulse" | grep -v egrep | head -40' 2>&1 +echo +echo '=== CDP / display ===' +docker exec douyinweb-neko-6 bash -lc 'echo DISPLAY=$DISPLAY; ls -la /tmp/.X11-unix 2>&1; curl -sS -m 3 http://127.0.0.1:9222/json/version 2>&1 | head -c 400; echo' 2>&1 +echo +echo '=== recent logs chrome/neko/x ===' +docker logs --tail 80 douyinweb-neko-6 2>&1 | tail -80 +echo +echo '=== chrome stderr if any ===' +docker exec douyinweb-neko-6 bash -lc 'ls -lt /var/log/supervisor/ 2>/dev/null | head -20; for f in /var/log/supervisor/*chrome* /var/log/supervisor/*browser* /var/log/neko* /home/neko/.config/chrome*/chrome_debug.log; do [ -f "$f" ] && echo ---- $f ---- && tail -40 "$f"; done' 2>&1 | tail -120 +echo +echo '=== browser-launch / entry ===' +docker exec douyinweb-neko-6 bash -lc 'ls -la /usr/bin/google-chrome* /usr/local/bin/*browser* /etc/neko/supervisord* 2>/dev/null; head -80 /usr/local/bin/browser-launch.sh 2>/dev/null || head -80 /usr/bin/browser-launch.sh 2>/dev/null || true' 2>&1 | head -100 +echo +echo '=== assign mapping neko 6 ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if int(g.get('neko_instance_id') or 0) == 6: + print({k: g.get(k) for k in ('id','name','neko_instance_id','neko_enabled','enabled','category','has_stream_key')}) +PY +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dylive_neko6_chrome.py b/scripts/_diag_dylive_neko6_chrome.py new file mode 100644 index 0000000..148380c --- /dev/null +++ b/scripts/_diag_dylive_neko6_chrome.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Fix dylive neko-6 Chrome FATAL without recreating container.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== google-chrome.conf ===' +docker exec douyinweb-neko-6 cat /etc/neko/supervisord/google-chrome.conf 2>&1 +echo +echo '=== host browser-launch overlay? ===' +ls -la /opt/douyinWEB/backend/neko/ 2>/dev/null | head -30 +find /opt/douyinWEB -name 'browser-launch*' 2>/dev/null | head +find /opt/douyinWEB -name '*google-chrome*' 2>/dev/null | head +echo +echo '=== try start chrome manually to capture stderr ===' +docker exec -u neko douyinweb-neko-6 bash -lc ' +export DISPLAY=:99.0 +export HOME=/home/neko +# show command from conf +grep -E "command=|environment=" /etc/neko/supervisord/google-chrome.conf +# run chrome briefly +timeout 8 google-chrome --version 2>&1 +timeout 12 google-chrome --no-first-run --no-default-browser-check --user-data-dir=/home/neko/.config/google-chrome --remote-debugging-port=9222 about:blank 2>&1 | tail -50 +echo EXIT:$? +' 2>&1 +echo +echo '=== dmesg / SIGILL hints ===' +dmesg -T 2>/dev/null | grep -iE 'chrome|sigill|segfault|killed process' | tail -20 +echo +echo '=== compare healthy launch on host scripts ===' +grep -Rnl 'jitless\|browser-launch\|no-wasm' /opt/douyinWEB/backend/neko /opt/douyinWEB/scripts 2>/dev/null | head -20 +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dylive_neko7_404.py b/scripts/_diag_dylive_neko7_404.py new file mode 100644 index 0000000..a9467b5 --- /dev/null +++ b/scripts/_diag_dylive_neko7_404.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + print("=== public probes ===") + with httpx.Client(timeout=20, follow_redirects=False) as c: + for u in [ + "https://dylive.nomadro.com/neko/7", + "https://dylive.nomadro.com/neko/7/", + "https://dylive.nomadro.com/neko/1/", + "https://dylive.nomadro.com/neko/8/", + ]: + try: + r = c.get(u) + loc = r.headers.get("location", "") + ct = r.headers.get("content-type", "")[:40] + print(f"{u} -> {r.status_code} loc={loc} ct={ct} body={r.text[:80]!r}") + except Exception as e: + print(u, "ERR", e) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + remote = r""" +echo '=== caddy sites mentioning neko ===' +grep -nR 'neko' /etc/caddy/sites/ 2>/dev/null | head -80 +echo '=== dylive site file ===' +ls /etc/caddy/sites/ | head +for f in /etc/caddy/sites/*dylive* /etc/caddy/sites/*nomadro*; do + [ -f "$f" ] || continue + echo "---- $f ----" + grep -nE 'neko|920|handle' "$f" | head -60 +done +echo '=== local ports ===' +ss -lntp | grep -E ':920[0-9]|:9199' || true +echo '=== docker neko 7 ===' +docker ps --format '{{.Names}} {{.Status}} {{.Ports}}' | grep -E 'neko-7|neko-8|neko-1' || true +curl -sS -m 4 -o /dev/null -w 'loop9206=%{http_code}\n' http://127.0.0.1:9206/ || true +curl -sS -m 4 -o /dev/null -w 'loop9200=%{http_code}\n' http://127.0.0.1:9200/ || true +""" + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_neko7_404.sh", "wb") as f: + f.write(remote.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_neko7_404.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_neko8.py b/scripts/_diag_dylive_neko8.py new file mode 100644 index 0000000..ad6563d --- /dev/null +++ b/scripts/_diag_dylive_neko8.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose why https://dylive.nomadro.com/neko/8/ fails.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +echo '=== public http ===' +curl -sS -m 8 -o /dev/null -w 'dylive_neko8=%{http_code} redirect=%{redirect_url}\n' https://dylive.nomadro.com/neko/8/ +curl -sS -m 8 -o /dev/null -w 'dylive_neko7=%{http_code}\n' https://dylive.nomadro.com/neko/7/ +curl -sS -m 8 -D - -o /dev/null https://dylive.nomadro.com/neko/8/ 2>&1 | head -30 + +echo '=== local containers ===' +docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep -E 'neko|NAMES' | head -40 + +echo '=== listening 920x ===' +ss -lntp | grep -E ':920[0-9]\b|:1920[0-9]\b' | head -40 + +echo '=== caddy neko routes (dylive) ===' +# find site config +for f in /etc/caddy/Caddyfile /etc/caddy/*.caddy /etc/caddy/conf.d/* /etc/caddy/sites/* /opt/caddy/* 2>/dev/null; do + [ -f "$f" ] || continue + if grep -q 'dylive\|neko/' "$f" 2>/dev/null; then + echo "-- $f --" + grep -nE 'neko/|920[0-9]|dylive' "$f" | head -60 + fi +done +ls /etc/caddy 2>/dev/null +ls /etc/caddy/sites-enabled /etc/caddy/conf.d 2>/dev/null + +echo '=== find dylive caddy ===' +grep -Rsl 'dylive.nomadro.com' /etc/caddy /opt /root 2>/dev/null | head -20 + +echo '=== compose / api neko expect ===' +ls /opt/douyinWEB/backend/data/neko 2>/dev/null | head +# how many assign slots +python3 - <<'PY' +import os, json +from pathlib import Path +root=Path('/opt/douyinWEB') +# quick env +for p in [root/'backend'/'.env', root/'.env', Path('/etc/douyinweb.env')]: + if p.exists(): + print('envfile', p) + for line in p.read_text(errors='replace').splitlines(): + if 'NEKO' in line.upper() or 'ASSIGN' in line.upper(): + print(' ', line[:160]) +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_dylive_neko8.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_dylive_neko8.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_neko8b.py b/scripts/_diag_dylive_neko8b.py new file mode 100644 index 0000000..d38906c --- /dev/null +++ b/scripts/_diag_dylive_neko8b.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +echo '=== neko-8 inspect ===' +docker inspect douyinweb-neko-8 --format 'Status={{.State.Status}} Exit={{.State.ExitCode}} OOM={{.State.OOMKilled}} Error={{.State.Error}} Finished={{.State.FinishedAt}} Started={{.State.StartedAt}}' +docker inspect douyinweb-neko-8 --format '{{json .HostConfig.PortBindings}}' | python3 -m json.tool 2>/dev/null | head -40 +docker inspect douyinweb-neko-7 --format 'neko7 ports={{json .HostConfig.PortBindings}}' | head -c 500; echo + +echo '=== neko-8 last logs ===' +docker logs --tail 80 douyinweb-neko-8 2>&1 | tail -80 + +echo '=== dmesg OOM hint ===' +dmesg -T 2>/dev/null | grep -iE 'oom|killed process|neko-8' | tail -15 + +echo '=== caddy dylive neko ===' +grep -Rsl 'dylive.nomadro.com' /etc/caddy 2>/dev/null +SITE=$(grep -Rsl 'dylive.nomadro.com' /etc/caddy 2>/dev/null | head -1) +echo "SITE=$SITE" +if [ -n "$SITE" ]; then + grep -nE 'neko/[0-9]|920[0-9]|handle_path|reverse_proxy' "$SITE" | head -80 +fi + +echo '=== local curl upstreams ===' +for p in 9207 9208 9206; do + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$p/ 2>/dev/null || echo fail) + echo "127.0.0.1:$p -> $code" +done + +echo '=== assign groups neko on vps db ===' +sqlite3 /opt/douyinWEB/backend/data/monitor.db "SELECT id,name,neko_instance_id,neko_enabled FROM yt_assign_groups ORDER BY neko_instance_id;" 2>/dev/null || \ +python3 - <<'PY' +import sqlite3 +db='/opt/douyinWEB/backend/data/monitor.db' +con=sqlite3.connect(db) +con.row_factory=sqlite3.Row +try: + rows=con.execute('select id,name,neko_instance_id,neko_enabled from yt_assign_groups order by neko_instance_id').fetchall() + for r in rows: + print(dict(r)) +except Exception as e: + print('db_err', e) +PY + +echo '=== free mem ===' +free -h | head -3 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_dylive_neko8b.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_dylive_neko8b.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_oom_one_neko.py b/scripts/_diag_dylive_oom_one_neko.py new file mode 100644 index 0000000..d2e72dd --- /dev/null +++ b/scripts/_diag_dylive_oom_one_neko.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Read-only: why dylive OOMs with a single Neko.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +_i, o, e = c.exec_command( + r""" +set +e +echo '=== mem/swap ===' +free -h +echo +echo '=== neko containers ===' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}}\t{{.Status}}\t{{.Size}}' | sort +echo +echo '=== top RSS (host) ===' +ps -eo pid,user,rss,comm,args --sort=-rss | head -25 | awk '{printf "%6s %8s %8.1fMB %s\n", $1,$2,$3/1024, substr($0, index($0,$4))}' +echo +echo '=== systemd Memory* / OOMScore ===' +for u in douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb douyinweb-s3 douyinweb-sw-filer douyinweb-sw-master douyinweb-sw-volume; do + st=$(systemctl is-active $u.service 2>/dev/null || echo missing) + mh=$(systemctl show $u.service -p MemoryCurrent,MemoryHigh,MemoryMax,OOMScoreAdjust --value 2>/dev/null | tr '\n' ' ') + echo "$u: $st | $mh" +done +echo +echo '=== docker stats (running) ===' +docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.CPUPerc}}' 2>/dev/null | head -30 +echo +echo '=== neko-12 cgroup / chrome split ===' +docker stats douyinweb-neko-12 --no-stream --format 'neko12 {{.MemUsage}} / limit {{.MemPerc}}' +docker exec douyinweb-neko-12 sh -c ' +echo chrome_procs: +for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null || true) + case "$cmd" in + *chrome*|*Chrome*) + rss=$(awk "/VmRSS:/{print \$2}" "$p/status" 2>/dev/null) + echo "$rss kB $cmd" | cut -c1-160 + ;; + esac +done 2>/dev/null | sort -nr | head -15 +' +echo +echo '=== slab / cache pressure ===' +awk '/^(Cached|Buffers|SReclaimable|MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit):/' /proc/meminfo +echo +echo '=== recent oom / sigill (last 15) ===' +dmesg -T 2>/dev/null | grep -iE 'oom-kill|Out of memory|invalid opcode' | tail -15 +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_dylive_short.py b/scripts/_diag_dylive_short.py new file mode 100644 index 0000000..da30f51 --- /dev/null +++ b/scripts/_diag_dylive_short.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Short probes: real IP HTTPS + light SSH on dylive.""" +from __future__ import annotations + +import ssl +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# HTTPS to real IP with SNI +ctx = ssl.create_default_context() +for path in ("/", "/youtube", "/api/health"): + url = f"https://107.173.30.245{path}" + req = urllib.request.Request(url, headers={"Host": "dylive.nomadro.com"}) + try: + with urllib.request.urlopen(req, timeout=12, context=ctx) as r: + print("sni", path, r.status) + except Exception as e: + print("sni", path, type(e).__name__, str(e)[:160]) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +print("ssh connecting...", flush=True) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, +) +print("ssh ok", flush=True) + +for cmd in ( + "uptime; free -m | head -2", + "systemctl is-active caddy douyinweb-api douyinweb-web", + "ss -lntp | grep -E ':443|:4015|:8014' | head -10", + "curl -sS -m 4 -o /dev/null -w 'w:%{http_code}\n' http://127.0.0.1:4015/youtube || echo wfail", + "curl -sS -m 4 -o /dev/null -w 'a:%{http_code}\n' http://127.0.0.1:8014/api/health || echo afail", + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort", +): + print(f"\n$ {cmd}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=25) + o.channel.settimeout(25) + try: + out = (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + out = f"TIMEOUT {ex}" + print(out, flush=True) + +c.close() +print("DONE") diff --git a/scripts/_diag_dylive_youtube_down.py b/scripts/_diag_dylive_youtube_down.py new file mode 100644 index 0000000..221df2b --- /dev/null +++ b/scripts/_diag_dylive_youtube_down.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Diagnose dylive.nomadro.com /youtube ERR_FAILED.""" +from __future__ import annotations + +import socket +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +print("=== local DNS/TCP ===", flush=True) +try: + ips = socket.getaddrinfo("dylive.nomadro.com", 443, type=socket.SOCK_STREAM) + print("resolve", sorted({x[4][0] for x in ips})) +except Exception as e: + print("dns_fail", e) + +for host, port in [("dylive.nomadro.com", 443), ("107.173.30.245", 443), ("107.173.30.245", 80)]: + s = socket.socket() + s.settimeout(5) + try: + s.connect((host, port)) + print(f"tcp {host}:{port} OK") + except Exception as e: + print(f"tcp {host}:{port} FAIL {e}") + finally: + s.close() + +ctx = ssl.create_default_context() +for url in ( + "https://dylive.nomadro.com/", + "https://dylive.nomadro.com/youtube", + "https://dylive.nomadro.com/api/health", + "http://107.173.30.245/", +): + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=15, context=ctx if url.startswith("https") else None) as r: + print(url, r.status, r.getheader("content-type"), "len", r.headers.get("content-length")) + except Exception as e: + print(url, "FAIL", type(e).__name__, e) + +print("\n=== SSH host ===", flush=True) +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("ssh_retry", i, e, flush=True) + time.sleep(2) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '--- load/mem ---' +uptime +free -h | head -2 +echo '--- units ---' +systemctl is-active caddy douyinweb-api douyinweb-web 2>/dev/null +systemctl --failed --no-pager 2>/dev/null | head -20 +echo '--- listen ---' +ss -lntp | grep -E ':443|:80|:4015|:8014' | head -20 +echo '--- curl local ---' +curl -sS -m 5 -o /dev/null -w 'loop_web:%{http_code}\n' http://127.0.0.1:4015/youtube || echo loop_web_fail +curl -sS -m 5 -o /dev/null -w 'loop_api:%{http_code}\n' http://127.0.0.1:8014/api/health || echo loop_api_fail +curl -sS -m 8 -o /dev/null -w 'caddy_https:%{http_code}\n' -k https://127.0.0.1/youtube -H 'Host: dylive.nomadro.com' || echo caddy_fail +curl -sS -m 8 -o /dev/null -w 'public:%{http_code}\n' https://dylive.nomadro.com/youtube || echo public_fail +echo '--- journal ---' +journalctl -u douyinweb-web -u douyinweb-api -u caddy --since '30 min ago' --no-pager 2>/dev/null | tail -60 +echo '--- docker neko mem ---' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' 2>/dev/null | grep neko | head +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_diag_dylive_yt_long.py b/scripts/_diag_dylive_yt_long.py new file mode 100644 index 0000000..e338af0 --- /dev/null +++ b/scripts/_diag_dylive_yt_long.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Diagnose yt-long on dylive — read only.""" +from __future__ import annotations + +import json +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def ssh_run(c, cmd, timeout=60): + print(f"\n===== {cmd[:100]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + out = o.read().decode("utf-8", "replace") + err = e.read().decode("utf-8", "replace") + if out: + print(out[:12000], flush=True) + if err.strip(): + print("[stderr]", err[:1500], flush=True) + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as ex: + print("ssh fail", ex, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + ssh_run( + c, + r""" +set -e +echo api=$(systemctl is-active douyinweb-api) +# settings keys related to yt long +sqlite3 /opt/douyinWEB/backend/data/monitor.db "SELECT key, substr(value,1,200) FROM settings WHERE key LIKE '%yt_long%' OR key LIKE '%ytlong%' OR key LIKE '%long%' ORDER BY key;" 2>/dev/null || \ +python3 - <<'PY' +import sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +cur=con.cursor() +for row in cur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1"): + print('table', row[0]) +PY +""", + ) + ssh_run( + c, + r""" +python3 - <<'PY' +import sqlite3, json +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +cur=con.cursor() +tables=[r[0] for r in cur.execute("SELECT name FROM sqlite_master WHERE type='table'")] +print('tables', tables) +# find yt long related +for t in tables: + if 'yt' in t.lower() or 'long' in t.lower() or 'clip' in t.lower() or 'upload' in t.lower(): + print('---', t) + try: + cols=[x[1] for x in cur.execute(f'PRAGMA table_info({t})')] + print('cols', cols) + n=cur.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0] + print('count', n) + rows=cur.execute(f'SELECT * FROM {t} ORDER BY rowid DESC LIMIT 8').fetchall() + for r in rows: + d=dict(r) + # trim + for k,v in list(d.items()): + if isinstance(v,str) and len(v)>120: d[k]=v[:120]+'...' + print(d) + except Exception as e: + print('err', e) +# settings +print('---settings yt/long/quota---') +try: + for r in cur.execute("SELECT key, value FROM settings WHERE key LIKE '%yt%' OR key LIKE '%long%' OR key LIKE '%quota%' OR key LIKE '%short%' ORDER BY key"): + v=r[1] + if isinstance(v,str) and len(v)>300: v=v[:300]+'...' + print(r[0], '=', v) +except Exception as e: + print('settings_err', e) +PY +""", + ) + ssh_run( + c, + r""" +journalctl -u douyinweb-api --since '2 hours ago' --no-pager 2>/dev/null | grep -iE 'yt.?long|yt_long|long.?upload|upload.*long|quota|403|429' | tail -60 +echo '---ffmpeg yt_long---' +pgrep -a ffmpeg 2>/dev/null | grep -i yt_long || echo none +ls -lt /opt/douyinWEB/backend/data/clips/yt_long 2>/dev/null | head -15 || echo no_dir +""", + ) + # local API probe via ssh curl + ssh_run( + c, + r""" +curl -sS -m 15 http://127.0.0.1:8014/api/yt-long/status 2>/dev/null | head -c 4000; echo +curl -sS -m 15 http://127.0.0.1:8014/api/yt-long 2>/dev/null | head -c 2000; echo +curl -sS -m 15 'http://127.0.0.1:8014/openapi.json' 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print('\n'.join(sorted(p for p in d.get('paths',{}) if 'yt' in p.lower() or 'long' in p.lower())[:40]))" 2>/dev/null || true +""", + ) + c.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_yt_long2.py b/scripts/_diag_dylive_yt_long2.py new file mode 100644 index 0000000..ece7d52 --- /dev/null +++ b/scripts/_diag_dylive_yt_long2.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Deeper yt-long diagnosis on dylive.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def run(c, cmd, timeout=60): + print(f"\n===== {cmd[:90]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + print(o.read().decode("utf-8", "replace")[:15000], flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:800], flush=True) + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as ex: + print(ex, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("fail") + + run(c, "df -h / /opt /opt/douyinWEB /opt/douyinWEB/backend/data 2>/dev/null; df -h | head -20") + run( + c, + r""" +python3 - <<'PY' +import sqlite3, time, json +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +cur=con.cursor() +# kv settings +print('---kv yt_long---') +for k,v in cur.execute("SELECT key,value FROM kv_settings WHERE key LIKE '%yt_long%' OR key LIKE '%disk%' ORDER BY key"): + print(k, '=', (v[:200]+'...') if len(str(v))>200 else v) +day='2026-09-13' +print('---status counts today---') +for r in cur.execute("SELECT status, COUNT(*) c FROM yt_long_jobs WHERE push_date=? GROUP BY status ORDER BY c DESC", (day,)): + print(dict(status=r[0], c=r[1])) +print('---errors today top---') +for r in cur.execute("SELECT COALESCE(error,''), COUNT(*) c FROM yt_long_jobs WHERE push_date=? GROUP BY 1 ORDER BY c DESC LIMIT 15", (day,)): + print(r[0][:120] or '(empty)', r[1]) +print('---uploaded today---') +print(cur.execute("SELECT COUNT(*) FROM yt_long_jobs WHERE push_date=? AND status='uploaded'", (day,)).fetchone()[0]) +print('---scheduled with clip---') +print(cur.execute("SELECT COUNT(*) FROM yt_long_jobs WHERE push_date=? AND status='scheduled' AND clip_path!=''", (day,)).fetchone()[0]) +print('---pending---', cur.execute("SELECT COUNT(*) FROM yt_long_jobs WHERE push_date=? AND status='pending'", (day,)).fetchone()[0]) +print('---recording/uploading---') +for st in ('recording','uploading','clipping','encoding'): + n=cur.execute("SELECT COUNT(*) FROM yt_long_jobs WHERE push_date=? AND status=?", (day,st)).fetchone()[0] + if n: print(st, n) +print('---channels enabled---') +cols=[x[1] for x in cur.execute('PRAGMA table_info(yt_long_channels)')] +print('cols', cols) +# guess enabled column +q="SELECT COUNT(*) FROM yt_long_channels" +print('channels_total', cur.execute(q).fetchone()[0]) +if 'enabled' in cols: + print('enabled', cur.execute("SELECT COUNT(*) FROM yt_long_channels WHERE enabled=1").fetchone()[0]) +# recent uploaded ever +print('---last uploaded jobs---') +for r in cur.execute("SELECT id,status,error,push_date,upload_at,youtube_video_id,substr(title,1,40) FROM yt_long_jobs WHERE status='uploaded' ORDER BY upload_at DESC LIMIT 5"): + print(r) +print('---disk_low jobs---') +print(cur.execute("SELECT COUNT(*) FROM yt_long_jobs WHERE error LIKE 'disk_low%'").fetchone()[0]) +for r in cur.execute("SELECT id,status,error,attempts,updated_at FROM yt_long_jobs WHERE error LIKE 'disk_low%' ORDER BY updated_at DESC LIMIT 5"): + print(r) +PY +""", + ) + run( + c, + r""" +# call status via python inside app context if possible +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +from app.yt_long_pipeline import yt_long_pipeline +from app import yt_long_db +cfg=db.get_settings_map() +keys=[k for k in sorted(cfg) if 'yt_long' in k] +for k in keys: + print(f'{k}={cfg.get(k)!r}') +print('---status---') +st=yt_long_pipeline.status_light() if hasattr(yt_long_pipeline,'status_light') else yt_long_pipeline.status() +import json +print(json.dumps(st, ensure_ascii=False, indent=2)[:3000]) +print('pipeline_task', getattr(yt_long_pipeline,'_task',None)) +PY +""", + ) + run(c, "du -sh /opt/douyinWEB/backend/data/clips/* 2>/dev/null | sort -h | tail -20; ls -la /opt/douyinWEB/backend/data/clips/ 2>/dev/null") + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_dylive_yt_long3.py b/scripts/_diag_dylive_yt_long3.py new file mode 100644 index 0000000..147cb60 --- /dev/null +++ b/scripts/_diag_dylive_yt_long3.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +du -xh /opt --max-depth=2 2>/dev/null | sort -h | tail -25 +echo --- +du -xh /var/lib/docker --max-depth=1 2>/dev/null | sort -h | tail -10 +echo --- +cd /opt/douyinWEB/backend && ./.venv/bin/python - <<'PY' +from app.clip_retention import disk_ok_for_record, disk_free_gb +from app import db +cfg=db.get_settings_map() +print('free_gb', disk_free_gb()) +print('clips_min_free_gb', cfg.get('clips_min_free_gb')) +print('disk_ok', disk_ok_for_record(cfg)) +PY +echo --- +# why pipeline not running after boot +journalctl -u douyinweb-api --since '2026-09-13 15:00' --no-pager | grep -iE 'yt_long|pipeline|boot' | tail -30 +""" +_i, o, e = c.exec_command(cmd, timeout=90) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err.strip(): + print("[stderr]", err[:1000]) +c.close() diff --git a/scripts/_diag_dylive_yt_long4.py b/scripts/_diag_dylive_yt_long4.py new file mode 100644 index 0000000..0ed70a7 --- /dev/null +++ b/scripts/_diag_dylive_yt_long4.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +du -xh / --max-depth=1 2>/dev/null | sort -h | tail -20 +echo --- +du -xh /var --max-depth=2 2>/dev/null | sort -h | tail -20 +echo --- +du -xh /opt/douyinWEB/backend --max-depth=2 2>/dev/null | sort -h | tail -20 +echo --- +# live api status via cookie login +python3 - <<'PY' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar() +opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +try: + r=opener.open(req, timeout=20) + print('login', r.status, r.read()[:200]) +except Exception as e: + print('login_fail', e) + # try alternate + req=urllib.request.Request('http://127.0.0.1:8014/api/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') + try: + r=opener.open(req, timeout=20) + print('login2', r.status, r.read()[:300]) + except Exception as e2: + print('login2_fail', e2) +for path in ['/api/yt-long/status','/api/yt-long/status?light=1']: + try: + r=opener.open('http://127.0.0.1:8014'+path, timeout=20) + print(path, r.read().decode()[:2000]) + except Exception as e: + print(path, e) +PY +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err.strip(): + print("[stderr]", err[:1500]) +c.close() diff --git a/scripts/_diag_ga_and_metrics.py b/scripts/_diag_ga_and_metrics.py new file mode 100644 index 0000000..5e7c3c7 --- /dev/null +++ b/scripts/_diag_ga_and_metrics.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import json +import sys +import urllib.request +import http.cookiejar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +echo '=== mem ===' +free -h +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo +echo '=== virtio ports ===' +ls -la /dev/virtio-ports 2>/dev/null || echo 'no virtio-ports' +ls -la /dev/vport* 2>/dev/null || true +echo '=== ga status ===' +systemctl status qemu-guest-agent --no-pager -l 2>&1 | head -40 +journalctl -u qemu-guest-agent -n 30 --no-pager 2>&1 | tail -40 +echo '=== try start ===' +systemctl start qemu-guest-agent 2>&1 || true +sleep 1 +systemctl is-active qemu-guest-agent || true +systemctl status qemu-guest-agent --no-pager -l 2>&1 | head -25 +""" + + +def main() -> int: + # public metrics + for base in ("https://dy.nomadro.com", "https://dy.nomadro.cn"): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + req = urllib.request.Request( + base + "/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + op.open(req, timeout=25) + raw = op.open(base + "/api/ops/host-metrics", timeout=25).read() + print(base, raw.decode()[:220], flush=True) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_ga_diag.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_ga_diag.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_diag_hysteria5_deep.py b/scripts/_diag_hysteria5_deep.py new file mode 100644 index 0000000..3b15ae8 --- /dev/null +++ b/scripts/_diag_hysteria5_deep.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Deep check hysteria5: DNS, UDP ports, Clash delay, sing-box inbound.""" +from __future__ import annotations + +import sys +import time +import urllib.parse + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" +NODE = "1d2da142-singbox_hysteria5" + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, port, user, pw, timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=70): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## VPS sing-box hysteria inbound", flush=True) +v = connect(22) +run( + v, + "python3 - <<'PY'\n" + "import json\n" + "p='/etc/v2ray-agent/sing-box/conf/config.json'\n" + "d=json.load(open(p))\n" + "for ib in d.get('inbounds') or []:\n" + " t=ib.get('type') or ''\n" + " tag=ib.get('tag') or ''\n" + " listen=ib.get('listen')\n" + " port=ib.get('listen_port') or ib.get('port')\n" + " if 'hysteria' in t.lower() or 'hysteria' in tag.lower() or 'tuic' in t.lower():\n" + " print(tag, t, listen, port)\n" + " # print users tags\n" + " users=(ib.get('users') or [])[:3]\n" + " for u in users:\n" + " print(' user', {k:u.get(k) for k in ('name','uuid','password') if k in u})\n" + "print('--- udp listen ---')\n" + "PY\n" + "ss -ulnp | grep -E 'sing|21825|30000|16113|32000' | head -30; " + "getent hosts specials.nomadro.live; dig +short specials.nomadro.live A 2>/dev/null | head -5", + t=40, +) +v.close() + +print("## physical: DNS + delay test via Clash API", flush=True) +g = connect(4014, "eric", "4669805") +q = urllib.parse.quote(NODE, safe="") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "getent hosts specials.nomadro.live; " + "dig +short specials.nomadro.live A 2>/dev/null | head -5; " + "timeout 3 bash -c \"echo >/dev/udp/specials.nomadro.live/21825\" 2>/dev/null && echo udp21825_send_ok || echo udp21825_send_fail; " + f"curl -sS -m 15 -X GET \"http://127.0.0.1:9999/proxies/{q}/delay?timeout=5000&url=http://www.gstatic.com/generate_204\"; echo; " + f"curl -sS -m 8 \"http://127.0.0.1:9999/proxies/{q}\" | python3 -m json.tool 2>/dev/null | head -60; " + "curl -sS -m 12 -X GET \"http://127.0.0.1:9999/proxies/1d2da142-singbox_tuic5/delay?timeout=5000&url=http://www.gstatic.com/generate_204\"; echo; " + "curl -sS -m 12 -X GET \"http://127.0.0.1:9999/proxies/1d2da142-VLESS_Reality_Vision5/delay?timeout=5000&url=http://www.gstatic.com/generate_204\"; echo" + "'", + t=80, +) +g.close() +print("DONE", flush=True) diff --git a/scripts/_diag_hysteria5_fw.py b/scripts/_diag_hysteria5_fw.py new file mode 100644 index 0000000..067f4e8 --- /dev/null +++ b/scripts/_diag_hysteria5_fw.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Why hysteria5 times out while tuic works. Check hop ports + firewall + tls.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pw, timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=60): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## VPS hysteria inbound detail + firewall", flush=True) +v = connect(22) +run( + v, + "python3 - <<'PY'\n" + "import json\n" + "from pathlib import Path\n" + "for p in [Path('/etc/v2ray-agent/sing-box/conf/config.json'), *Path('/etc/v2ray-agent/sing-box/conf').glob('*.json')]:\n" + " try: d=json.loads(p.read_text())\n" + " except Exception: continue\n" + " items=d if isinstance(d,list) else ([d] if 'type' in d else d.get('inbounds') or [])\n" + " if isinstance(d,dict) and 'inbounds' not in d and d.get('type'): items=[d]\n" + " for ib in items:\n" + " if not isinstance(ib,dict): continue\n" + " if 'hysteria' not in str(ib.get('type','')).lower() and 'hysteria' not in str(ib.get('tag','')).lower():\n" + " continue\n" + " print('FILE', p)\n" + " print(json.dumps({k:ib.get(k) for k in ('type','tag','listen','listen_port','up_mbps','down_mbps','tls','obfs','users','masquerade')}, indent=2)[:2500])\n" + "PY\n" + "echo '--- ufw ---'; ufw status | grep -E '21825|30000|16113|32000|UDP' | head -30; " + "echo '--- iptables ---'; iptables -L INPUT -n | grep -E '21825|30000|16113' | head -20; " + "journalctl -u sing-box --since '10 min ago' --no-pager | grep -i hysteria | tail -30", + t=50, +) +v.close() + +print("## physical: client yaml snippet + delay without hop?", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "sed -n \"177,218p\" /tmp/ShellCrash/config.yaml; " + "echo ---; " + # force delay again + "curl -sS -m 12 -G \"http://127.0.0.1:9999/proxies/1d2da142-singbox_hysteria5/delay\" --data-urlencode \"url=http://www.gstatic.com/generate_204\" --data-urlencode \"timeout=8000\"; echo; " + "curl -sS -m 12 -G \"http://127.0.0.1:9999/proxies/1d2da142-singbox_tuic5/delay\" --data-urlencode \"url=http://www.gstatic.com/generate_204\" --data-urlencode \"timeout=5000\"; echo" + "'", + t=40, +) +g.close() +print("DONE", flush=True) diff --git a/scripts/_diag_hysteria5_ping.py b/scripts/_diag_hysteria5_ping.py new file mode 100644 index 0000000..b9f7242 --- /dev/null +++ b/scripts/_diag_hysteria5_ping.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Diagnose why 1d2da142-singbox_hysteria5 is not pingable. Live flush.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" +NEEDLE = "1d2da142" +NEEDLE2 = "hysteria5" + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, port, user, pw, timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=60): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## VPS sing-box + configs mentioning node", flush=True) +v = connect(22) +run(v, "systemctl is-active sing-box; systemctl status sing-box --no-pager -l | head -25") +run( + v, + f"find /etc /opt /root /usr -maxdepth 4 \\( -name '*sing*' -o -name '*hysteria*' -o -name 'config.json' \\) 2>/dev/null | head -40; " + f"grep -Rsn --include='*.json' --include='*.yaml' --include='*.yml' --include='*.toml' " + f"-e '{NEEDLE}' -e '{NEEDLE2}' -e 'singbox_hysteria' /etc /opt /root 2>/dev/null | head -40", + t=90, +) +run( + v, + # common sing-box clash API / experimental + "ss -lntp | grep -iE 'sing|2080|2090|9090|9091|7890|1080' || true; " + "command -v sing-box; sing-box version 2>/dev/null | head -5; " + "ls /etc/sing-box 2>/dev/null; ls /etc/sing-box/ 2>/dev/null", +) +v.close() + +print("## physical ShellCrash proxies (via FRP)", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + f"grep -Rsn --include=\"*.yaml\" --include=\"*.yml\" --include=\"*.json\" -e \"{NEEDLE}\" -e \"{NEEDLE2}\" " + f"/etc/ShellCrash /tmp/ShellCrash 2>/dev/null | head -40; " + "curl -sS -m 8 http://127.0.0.1:9999/proxies 2>/dev/null | python3 -c " + "\"import sys,json; d=json.load(sys.stdin); ps=d.get(\\\"proxies\\\") or d; " + "keys=[k for k in (ps if isinstance(ps,dict) else {}) if \\\"hysteria\\\" in k.lower() or \\\"1d2da\\\" in k.lower()]; " + "print(\\\"match_keys\\\", keys[:30]); " + "[print(k, (ps.get(k)||{}).get(\\\"type\\\"), (ps.get(k)||{}).get(\\\"history\\\",[{}])[-1] if (ps.get(k)||{}).get(\\\"history\\\") else None) for k in keys[:15]]\" " + "2>/dev/null || echo no_clash_api; " + "curl -sS -m 5 http://127.0.0.1:9999/version; echo" + "'", + t=50, +) +g.close() +print("DONE", flush=True) diff --git a/scripts/_diag_neko3_ports.py b/scripts/_diag_neko3_ports.py new file mode 100644 index 0000000..8fee6f0 --- /dev/null +++ b/scripts/_diag_neko3_ports.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) +_i, o, e = c.exec_command( + r""" +set +e +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}} {{.Ports}}' +echo '--- inspect 3 ports ---' +docker inspect douyinweb-neko-3 --format '{{json .HostConfig.PortBindings}}' +echo +docker inspect douyinweb-neko-3 --format '{{json .NetworkSettings.Ports}}' +echo +echo '--- logs ---' +docker logs --tail 40 douyinweb-neko-3 2>&1 +echo '--- compose ---' +ls -la /opt/douyinWEB/backend/data/neko/ 2>/dev/null | head +head -80 /opt/douyinWEB/backend/data/neko/docker-compose.yml 2>/dev/null | head -80 +echo '--- ss 920 ---' +ss -lntp | grep 920 || echo none +echo '--- dylive caddy neko3 ---' +grep -A5 'handle_path /neko/3' /etc/caddy/sites/dylive.nomadro.com.caddy | head -10 +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_neko3_tm2.py b/scripts/_diag_neko3_tm2.py new file mode 100644 index 0000000..689b11e --- /dev/null +++ b/scripts/_diag_neko3_tm2.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +N=douyinweb-neko-3 +echo === mounts === +docker inspect "$N" --format '{{range .Mounts}}{{.Source}} -> {{.Destination}} ({{.Mode}}){{"\n"}}{{end}}' | head -40 +echo === inside seed/liveops === +docker exec "$N" bash -lc 'ls -la /etc/neko/live-ops-extension/manifest.json /etc/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json 2>&1; ls /etc/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/ 2>&1; ls /home/neko/.config/google-chrome/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/ 2>&1' +echo === env NEKO_* === +docker exec "$N" bash -lc 'env | grep -E "^NEKO_" | sort' +echo === supervisord chrome === +docker exec "$N" bash -lc 'grep -A30 -E "program:google-chrome|browser-launch" /etc/neko/supervisord.conf /etc/supervisor/conf.d/* 2>/dev/null | head -80' +echo === full chrome argv via python === +docker exec "$N" python3 -c 'import os; p="/proc/1066/cmdline"; print(open(p,"rb").read().replace(b"\0",b"\n").decode("utf-8","replace"))' +echo === prefs via python file === +docker exec "$N" python3 -c 'import json;from pathlib import Path;b=Path("/home/neko/.config/google-chrome/Default");p=b/"Preferences";d=json.loads(p.read_text());ext="dhdgffkkebhmkfjojejmpbldmpobfkfo";e=((d.get("extensions")or{}).get("settings")or{}).get(ext)or{};print("size",p.stat().st_size);print(e);print("keys",list(((d.get("extensions")or{}).get("settings")or{}).keys())[:20]);print("files",(b/"Extensions"/ext).exists(), list((b/"Extensions").iterdir()) if (b/"Extensions").exists() else None)' +echo === which browser-launch === +docker exec "$N" bash -lc 'ls -la /etc/neko/browser-launch.sh; head -5 /etc/neko/browser-launch.sh; sed -n "301,335p" /etc/neko/browser-launch.sh' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_neko3_tm2.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_diag_neko3_tm2.sh", + timeout=90, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_neko3_tm3.py b/scripts/_diag_neko3_tm3.py new file mode 100644 index 0000000..504971b --- /dev/null +++ b/scripts/_diag_neko3_tm3.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +N=douyinweb-neko-3 +echo === children of browser-launch === +docker exec "$N" python3 - <<'PY' +import os, json, urllib.request +# find all chrome-related cmdlines +for pid in sorted(os.listdir("/proc"), key=lambda x: int(x) if x.isdigit() else 0): + if not pid.isdigit(): + continue + try: + raw = open(f"/proc/{pid}/cmdline", "rb").read() + except Exception: + continue + if not raw: + continue + cmd = raw.replace(b"\0", b" ").decode("utf-8", "replace") + if "chrome" not in cmd.lower() and "browser-launch" not in cmd: + continue + if "--type=" in cmd: + continue + print("--- PID", pid, "ppid", open(f"/proc/{pid}/status").read().split("PPid:")[1].split()[0]) + print(cmd[:500]) + if "load-extension" in cmd: + for part in raw.split(b"\0"): + if b"load-extension" in part or b"user-data" in part: + print(" FLAG", part.decode()) +PY +echo === CDP tabs/sw === +docker exec "$N" python3 - <<'PY' +import json, urllib.request +try: + tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as e: + print("cdp_err", e) + tabs = [] +print("tabs", len(tabs)) +for t in tabs: + print(t.get("type"), (t.get("title") or "")[:40], (t.get("url") or "")[:120]) +PY +echo === simulate extension_flags logic === +docker exec "$N" sh - <<'SH' +set -eu +family=google-chrome +profile_dir=/home/neko/.config/google-chrome +NEKO_LIVE_OPS_EXTENSION=1 +NEKO_LIVE_OPS_EXTENSION_DIR=/etc/neko/live-ops-extension +NEKO_TAMPERMONKEY_SEED_DIR=/etc/neko/tampermonkey-seed +extension_flags="" +case "${NEKO_LIVE_OPS_EXTENSION:-1}" in + 0|false|FALSE|off|OFF|disable|disabled) ;; + *) + live_ops_extension_dir="${NEKO_LIVE_OPS_EXTENSION_DIR:-/etc/neko/live-ops-extension}" + if [ -f "$live_ops_extension_dir/manifest.json" ]; then + extension_flags="--load-extension=${live_ops_extension_dir}" + fi + ;; +esac +tm_ext_id="dhdgffkkebhmkfjojejmpbldmpobfkfo" +tm_load_dir="" +for candidate in \ + "${NEKO_TAMPERMONKEY_SEED_DIR:-/etc/neko/tampermonkey-seed}/Default/Extensions/$tm_ext_id"/*/manifest.json \ + "$profile_dir/Default/Extensions/$tm_ext_id"/*/manifest.json +do + echo "cand: $candidate exists=$( [ -f "$candidate" ] && echo y || echo n )" + if [ -f "$candidate" ]; then + tm_load_dir="$(dirname "$candidate")" + break + fi +done +echo "tm_load_dir=$tm_load_dir" +if [ -n "$tm_load_dir" ]; then + if [ -n "$extension_flags" ]; then + extension_flags="${extension_flags},${tm_load_dir}" + else + extension_flags="--load-extension=${tm_load_dir}" + fi +fi +echo "extension_flags=$extension_flags" +SH +echo === google-chrome.conf === +docker exec "$N" cat /etc/neko/supervisord/google-chrome.conf 2>/dev/null || docker exec "$N" ls /etc/neko/supervisord/ /etc/supervisor/conf.d/ 2>&1 +# find conf on host +cat /opt/douyinWEB/backend/neko/google-chrome.conf 2>/dev/null | head -40 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_neko3_tm3.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_diag_neko3_tm3.sh", + timeout=90, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_neko3_tm4.py b/scripts/_diag_neko3_tm4.py new file mode 100644 index 0000000..66fd3e9 --- /dev/null +++ b/scripts/_diag_neko3_tm4.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# Avoid heredocs: one docker-exec python -c at a time +CMDS = [ + "docker exec douyinweb-neko-3 supervisorctl status google-chrome", + "docker exec douyinweb-neko-3 wc -l /etc/neko/browser-launch.sh; docker exec douyinweb-neko-3 sed -n '1,15p' /etc/neko/browser-launch.sh", + "docker exec douyinweb-neko-3 sed -n '250,340p' /etc/neko/browser-launch.sh", + """docker exec douyinweb-neko-3 python3 -c "import os; ids=[p for p in os.listdir('/proc') if p.isdigit()]; +print('pids',len(ids)); +[ +print(pid, open('/proc/%s/cmdline'%pid,'rb').read().replace(b'\\x00',b' ').decode('utf-8','replace')[:300]) +for pid in ids +if b'chrome' in open('/proc/%s/cmdline'%pid,'rb').read().lower() or b'browser-launch' in open('/proc/%s/cmdline'%pid,'rb').read() +] +" """.replace("\n", " "), + 'docker exec douyinweb-neko-3 sh -c \'tail -n 80 /var/log/neko/google-chrome.log 2>/dev/null || tail -n 80 /var/log/supervisor/google-chrome*.log 2>/dev/null; ls -la /var/log/neko/ 2>/dev/null | head\'', + 'docker exec douyinweb-neko-3 python3 -c "import json,urllib.request; print(json.loads(urllib.request.urlopen(\'http://127.0.0.1:9222/json/version\',timeout=3).read()))"', +] + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + for cmd in CMDS: + print("\n#####", cmd[:120]) + _i, o, e = c.exec_command( + f"echo '4669805' | sudo -S -p '' bash -lc {cmd!r}", + timeout=60, + ) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[:4000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_neko3_tm_now.py b/scripts/_diag_neko3_tm_now.py new file mode 100644 index 0000000..65ce550 --- /dev/null +++ b/scripts/_diag_neko3_tm_now.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +N=douyinweb-neko-3 +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +echo === chrome === +docker exec "$N" supervisorctl status google-chrome +echo === cmdline === +docker exec "$N" bash -lc 'ps -ef | grep -E "[g]oogle-chrome --" | head -3' +echo === load-extension from /proc === +docker exec "$N" bash -lc 'for p in /proc/[0-9]*; do + [ -r "$p/cmdline" ] || continue + tr "\0" "\n" < "$p/cmdline" 2>/dev/null | grep -qx google-chrome || continue + echo PID ${p#/proc/} + tr "\0" "\n" < "$p/cmdline" | grep -E "load-extension|user-data-dir|disable-extensions" || echo "(no load-extension flags)" + break +done' +echo === prefs+files === +docker exec "$N" python3 - <<'PY' +import json +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +base=Path("/home/neko/.config/google-chrome/Default") +pref=base/"Preferences" +print("prefs_exists", pref.exists(), "size", pref.stat().st_size if pref.exists() else 0) +d=json.loads(pref.read_text()) +e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("tm_state", e.get("state"), "location", e.get("location"), "path", e.get("path")) +print("tm_disable", e.get("disable_reasons")) +print("ext_manifest", (base/"Extensions"/ext/"5.5.0_0"/"manifest.json").exists()) +print("seed_manifest", Path("/etc/neko/tampermonkey-seed/Default/Extensions/"+ext+"/5.5.0_0/manifest.json").exists()) +print("live_ops", Path("/etc/neko/live-ops-extension/manifest.json").exists()) +print("ext_ids", list(((d.get("extensions") or {}).get("settings") or {}).keys())[:12]) +PY +echo === CDP === +docker exec "$N" python3 - <<'PY' +import json, urllib.request +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +print("tabs", len(tabs)) +for t in tabs: + u=t.get("url") or "" + ty=t.get("type") or "" + if "extension" in u or "dhdgff" in u or ty=="service_worker" or "chrome-extension" in u: + print(ty, (t.get("title") or "")[:50], u[:160]) +PY +echo === policies === +docker exec "$N" bash -lc 'ls -la /etc/opt/chrome/policies/managed/ 2>/dev/null; head -c 2000 /etc/opt/chrome/policies/managed/*.json 2>/dev/null; echo' +echo === chrome stderr / openbox last === +docker exec "$N" bash -lc 'ls -lt /var/log/supervisor/ 2>/dev/null | head -10; tail -n 40 /var/log/supervisor/google-chrome*.log 2>/dev/null | tail -40' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_neko3_tm.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_diag_neko3_tm.sh", + timeout=90, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_neko_business_recheck.py b/scripts/_diag_neko_business_recheck.py new file mode 100644 index 0000000..26f1f1a --- /dev/null +++ b/scripts/_diag_neko_business_recheck.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Re-analyze Neko path for VPS hub + physical ops-neko (CN WG preferred). Read-only.""" +from __future__ import annotations + +import json +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + host, port, user, pw, + timeout=45, banner_timeout=120, + allow_agent=False, look_for_keys=False, + ) + return c + except Exception as ex: + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("===== PUBLIC CN vs COM neko/ops =====", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for url in [ + "https://dy.nomadro.cn/api/health", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/ops-neko/1/", + "https://dylive.nomadro.com/neko/1/", + "https://dylive.nomadro.com/ops-neko/1/", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(url) + print(f"{r.status_code} {url} loc={r.headers.get('location','')[:60]}", flush=True) + except Exception as ex: + print(f"ERR {url} {ex}", flush=True) + +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print("===== VPS (dylive hub) neko/ops perspective =====", flush=True) +print(run(v, r""" +set +e +echo '--- dylive local neko containers ---' +docker ps -a --format '{{.Names}} {{.Status}} {{.Ports}}' | grep -iE 'douyinweb-neko|ops-neko' | head -30 +echo '--- who owns 9200-9207 on VPS ---' +ss -lntp | grep -E ':(920[0-7]|1820[0-7])\b' | head -20 +echo '--- frp-aux still binding neko ports? ---' +systemctl is-active dy-frp-http-aux +# does dylive caddy have ops-neko? +grep -c 'ops-neko' /etc/caddy/sites/dylive.nomadro.com.caddy +grep -nE 'ops-neko|neko/1' /etc/caddy/sites/dylive.nomadro.com.caddy | head -15 +echo '--- login + assign/ops sync status (need cookie) ---' +# try admin login +CS=$(mktemp) +curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' | head -c 200; echo +echo '--- host-profile ---' +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/ops/host-profile | head -c 600; echo +echo '--- yt assign groups neko fields ---' +curl -sS -m 15 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups 2>/dev/null | python3 -c ' +import sys,json +raw=sys.stdin.read() +try: d=json.loads(raw) +except Exception as e: print("parse fail",e,raw[:200]); raise SystemExit +rows=d if isinstance(d,list) else d.get("groups") or d.get("items") or d.get("data") or [] +print("count", len(rows) if isinstance(rows,list) else type(rows)) +if isinstance(rows, list): + for g in rows[:20]: + print({ + "name": (g.get("name") or g.get("title") or "")[:40], + "neko_enabled": g.get("neko_enabled"), + "neko_instance_id": g.get("neko_instance_id"), + "desktop_target": g.get("desktop_target") or g.get("neko_desktop_target"), + "ops_bound": g.get("ops_neko_bound"), + "ops_slot": g.get("ops_neko_slot"), + "ops_url": (g.get("ops_neko_open_url") or "")[:80], + "neko_url": (g.get("neko_open_url") or g.get("open_url") or "")[:80], + }) +' +echo '--- ops peer / remote catalog ---' +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/ops/neko/peer 2>/dev/null | head -c 500; echo +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/ops/neko/remote-catalog 2>/dev/null | head -c 800; echo +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/ops/neko/sync-status 2>/dev/null | head -c 500; echo +echo '--- neko status api ---' +curl -sS -m 10 -b "$CS" http://127.0.0.1:8014/api/youtube/neko/status 2>/dev/null | head -c 800; echo +rm -f "$CS" +"""), flush=True) +v.close() + +p = ssh("107.173.30.245", 4014, "eric", "4669805") +print("===== PHYSICAL (ops-neko edge) =====", flush=True) +print(run(p, r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +CS=$(mktemp) +curl -sS -m 15 --noproxy "*" -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H "Content-Type: application/json" \ + -d "{\"username\":\"hackrobot\",\"password\":\"Xiao4669805@\"}" | head -c 200; echo +echo "--- host-profile ---" +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/ops/host-profile | head -c 700; echo +echo "--- peer / sync ---" +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/ops/neko/peer | head -c 600; echo +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/ops/neko/sync-status | head -c 600; echo +echo "--- ops instances ---" +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/ops/neko/instances 2>/dev/null | python3 -c " +import sys,json +raw=sys.stdin.read() +try: d=json.loads(raw) +except Exception as e: print(raw[:300]); raise SystemExit +rows=d if isinstance(d,list) else d.get(\"instances\") or d.get(\"items\") or [] +print(\"count\", len(rows)) +for r in rows[:15]: + print({k:r.get(k) for k in (\"slot\",\"name\",\"want_running\",\"running\",\"open_url\",\"bind_remote_group_id\",\"public_url\") if k in r or True}) + print(\" open\", (r.get(\"open_url\") or r.get(\"public_url\") or \"\")[:100]) +" +echo "--- nat1to1 on running ops/neko ---" +for c in douyinweb-ops-neko-1 douyinweb-neko-1; do + echo "== $c ==" + docker inspect "$c" --format "{{json .Config.Env}}" 2>/dev/null | tr "," "\n" | grep -E "NAT1TO1|BITRATE|MAX_FPS|DESKTOP_SCREEN|ICELITE|UDPMUX|EPR|BROWSER_PROXY|START_URL" || echo missing +done +echo "--- wg-dy-cn vs wg-dy ---" +wg show wg-dy-cn latest-handshakes +wg show wg-dy latest-handshakes +ping -c 2 -W 2 10.9.0.1 | tail -3 +ping -c 2 -W 2 10.8.0.1 | tail -3 +# can CN edge reach phys neko via 10.9.0.2? +curl -sS -m 5 --noproxy "*" -o /dev/null -w "local_ops1=%{http_code}\n" http://127.0.0.1:18200/ +curl -sS -m 5 --noproxy "*" -o /dev/null -w "local_neko1=%{http_code}\n" http://127.0.0.1:9200/ +echo "--- preferred base / settings ---" +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/settings 2>/dev/null | python3 -c " +import sys,json +raw=sys.stdin.read() +try: d=json.loads(raw) +except Exception: print(raw[:200]); raise SystemExit +if isinstance(d, dict): + for k in sorted(d): + if any(x in k.lower() for x in (\"neko\",\"nat\",\"ops\",\"public\",\"domain\")): + v=d[k] + if isinstance(v,str) and len(v)>120: v=v[:120] + print(k, \"=\", v) +" 2>/dev/null | head -60 +rm -f "$CS" +echo "--- mem ---" +free -h | head -3 +' +"""), flush=True) +p.close() +print("DONE", flush=True) diff --git a/scripts/_diag_neko_opt_probe.py b/scripts/_diag_neko_opt_probe.py new file mode 100644 index 0000000..98a14bd --- /dev/null +++ b/scripts/_diag_neko_opt_probe.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Neko optimization + CN ICE path probes (read-only).""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, banner_timeout=120, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +print("===== CN ops-neko HTTP + ICE ports reachability =====", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for url in [ + "https://dy.nomadro.cn/ops-neko/1/", + "https://dy.nomadro.cn/ops-neko/2/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/neko/3/", + ]: + try: + r = cl.get(url) + print(f"{r.status_code} {url}", flush=True) + except Exception as ex: + print(f"ERR {url} {ex}", flush=True) + +# Can we TCP-reach Tencent NAT mux from outside? (ICE candidate IP) +# 62300 = ops-neko-1 UDPMUX; don't send attack payloads — just TCP connect check if any +import socket +for host, port, label in [ + ("82.157.112.245", 62300, "ops1-mux"), + ("82.157.112.245", 62301, "ops2-mux"), + ("82.157.112.245", 52300, "neko1-mux"), + ("107.173.30.245", 62300, "vps-ops1-mux-should-fail-or-dnat"), +]: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(4) + try: + s.connect((host, port)) + print(f"TCP OK {label} {host}:{port}", flush=True) + except Exception as ex: + print(f"TCP FAIL {label} {host}:{port} {type(ex).__name__}", flush=True) + finally: + s.close() + +p = ssh("107.173.30.245", 4014, "eric", "4669805") +print("===== PHYS neko fleet load + exclusive mode =====", flush=True) +run( + p, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +echo "--- docker stats snapshot ---" +docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" 2>/dev/null | grep -iE "neko|ops|NAME" | head -25 +echo "--- how many chrome/neko ---" +docker ps --format "{{.Names}} {{.Status}}" | grep -i neko +echo "--- settings neko exclusive / bitrate ---" +CS=$(mktemp) +curl -sS -m 10 --noproxy "*" -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H "Content-Type: application/json" \ + -d "{\"username\":\"hackrobot\",\"password\":\"Xiao4669805@\"}" >/dev/null +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/settings | python3 -c " +import sys,json +d=json.load(sys.stdin) +keys=[k for k in d if any(x in k.lower() for x in (\"neko\",\"exclusive\",\"bitrate\",\"fps\",\"screen\",\"solo\",\"single\"))] +for k in sorted(keys): + print(k, \"=\", d[k]) +" +echo "--- assign on physical (if any) ---" +curl -sS -m 10 --noproxy "*" -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups 2>/dev/null | python3 -c " +import sys,json +raw=sys.stdin.read() +d=json.loads(raw) +rows=d if isinstance(d,list) else d.get(\"groups\") or [] +print(\"phys groups\", len(rows)) +en=sum(1 for g in rows if g.get(\"neko_enabled\")) +print(\"neko_enabled\", en) +" 2>/dev/null +rm -f "$CS" +echo "--- shellcrash 7890 ---" +ss -lntp | grep 7890 || echo no7890 +curl -sS -m 4 --noproxy "*" -o /dev/null -w "proxy_port=%{http_code}\n" http://127.0.0.1:7890/ || true +' +""", +) +p.close() + +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print("===== VPS: can local neko start? port conflict =====", flush=True) +run( + v, + r""" +set +e +# try explain conflict +ss -lntp | grep ':9202' +docker start douyinweb-neko-3 2>&1 | tail -5 +docker ps -a --filter name=douyinweb-neko-3 --format '{{.Names}} {{.Status}}' +# recent error +docker inspect douyinweb-neko-3 --format '{{.State.Error}} {{.State.Status}}' 2>/dev/null +# dylive open for neko_enabled local group — what does HTTP actually serve? +# Compare Set-Cookie / title only +curl -sS -m 8 https://dylive.nomadro.com/neko/3/ | head -c 180; echo +curl -sS -m 8 https://dy.nomadro.cn/neko/3/ | head -c 180; echo +""", +) +v.close() +print("DONE", flush=True) diff --git a/scripts/_diag_neko_prefer_restore.py b/scripts/_diag_neko_prefer_restore.py new file mode 100644 index 0000000..50f0c92 --- /dev/null +++ b/scripts/_diag_neko_prefer_restore.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, banner_timeout=120, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=60): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +# restore: stop neko-3 if we started it during probe (was Exited before) +run( + v, + r""" +set +e +# only stop if it was our accidental start; leave others alone +docker stop douyinweb-neko-3 >/dev/null 2>&1 +docker ps -a --filter name='^douyinweb-neko-' --format '{{.Names}} {{.Status}}' | head -20 +echo '--- prefer fields ---' +CS=$(mktemp) +curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 15 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups | python3 -c ' +import sys,json +d=json.load(sys.stdin) +rows=d if isinstance(d,list) else d.get("groups") or [] +for g in rows: + print({ + "name": (g.get("name") or "")[:28], + "prefer": g.get("neko_open_prefer"), + "src": g.get("neko_open_source"), + "open": (g.get("neko_open_url") or "")[:70], + "local": (g.get("neko_local_studio_url") or "")[:50], + "ops": (g.get("ops_neko_open_url") or "")[:50], + "neko_en": g.get("neko_enabled"), + "local_id": g.get("neko_instance_id"), + "ops_slot": g.get("ops_neko_slot"), + }) +' +rm -f "$CS" +echo '--- 127 vs 0.0.0.0 bind on 9202 ---' +ss -lntp | grep ':9202' +""", +) +v.close() +print("DONE") diff --git a/scripts/_diag_nomadvlog_flap.py b/scripts/_diag_nomadvlog_flap.py new file mode 100644 index 0000000..b211fd5 --- /dev/null +++ b/scripts/_diag_nomadvlog_flap.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +"""Diagnose nomadvlog start/stop flap on dylive.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +BASE = "https://dylive.nomadro.com" +GID_HINT = "nomadvlog" + +REMOTE = r""" +set -e +GID=$(sqlite3 /opt/douyinWEB/backend/data/monitor.db "SELECT id FROM yt_assign_groups WHERE lower(name) LIKE '%nomadvlog%' LIMIT 1;") +echo "GID=$GID" +echo "=== group ===" +sqlite3 -header -column /opt/douyinWEB/backend/data/monitor.db "SELECT id,name,category,enabled,neko_instance_id,substr(youtube_channel_id,1,20) AS yt FROM yt_assign_groups WHERE id='$GID';" +echo "=== relay_state ===" +sqlite3 -header -column /opt/douyinWEB/backend/data/monitor.db "SELECT group_id,status,source_room_id,anchor_name,ffmpeg_pid,substr(error,1,120) AS err,datetime(updated_at,'unixepoch','+8 hours') AS bj_upd,datetime(started_at,'unixepoch','+8 hours') AS bj_start FROM youtube_relay_state WHERE group_id='$GID';" +echo "=== recent_log tail ===" +sqlite3 /opt/douyinWEB/backend/data/monitor.db "SELECT recent_log FROM youtube_relay_state WHERE group_id='$GID';" | tail -c 4000 +echo +echo "=== events last 18h mentioning nomadvlog / relay ===" +sqlite3 -header -column /opt/douyinWEB/backend/data/monitor.db " +SELECT datetime(created_at,'unixepoch','+8 hours') AS bj, kind, level, substr(message,1,140) AS msg +FROM events +WHERE created_at > strftime('%s','now')-18*3600 + AND ( + message LIKE '%nomadvlog%' + OR message LIKE '%$GID%' + OR (kind LIKE '%relay%' OR kind LIKE '%youtube%' OR kind LIKE '%live%') AND message LIKE '%停%' + OR message LIKE '%source_switch%' + OR message LIKE '%outside_slot%' + OR message LIKE '%开播%' + OR message LIKE '%推流%' + ) +ORDER BY created_at DESC LIMIT 80; +" +echo "=== settings ===" +sqlite3 -header -column /opt/douyinWEB/backend/data/monitor.db " +SELECT key,value FROM kv_settings +WHERE key IN ( + 'youtube_relay_enabled','youtube_relay_time_slot_mode','youtube_relay_exclusive_live', + 'youtube_relay_respect_schedule','youtube_relay_on_air_deadline_sec' +); +" +echo "=== schedule active now ===" +cd /opt/douyinWEB/backend +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import sys +sys.path.insert(0,'/opt/douyinWEB/backend') +from app import yt_assign_db +sched=yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) +print('beijing_hint', sched.get('beijing_hint') or sched.get('now_beijing') or sched.get('push_date')) +for c in (sched.get('channels') or []): + name=str(c.get('name') or '') + if 'nomadvlog' in name.lower() or c.get('active'): + print('CH', name, 'active=',c.get('active'), 'window=',c.get('window') or c.get('slot') or c.get('label'), 'gid=',c.get('group_id'), 'aliases=',c.get('alias_group_ids')) +print('windows', (sched.get('windows') or sched.get('slots') or '')[:500] if isinstance(sched.get('windows') or sched.get('slots'), str) else json.dumps(sched.get('windows') or sched.get('slots') or [], ensure_ascii=False)[:800]) +import json +PY +echo "=== journal relay/nomadvlog last 200 ===" +journalctl -u douyinweb-api.service --since '18 hours ago' --no-pager 2>/dev/null | grep -iE 'nomadvlog|source_switch|outside_slot|on_air|invalid|halt|exclusive|45f9bd79' | tail -120 || true +""" + + +def main(): + # public API peek + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + op.open( + urllib.request.Request( + BASE + "/api/auth/login", + data=data, + method="POST", + headers={"Content-Type": "application/json"}, + ), + timeout=30, + ) + with op.open(urllib.request.Request(BASE + "/api/youtube/relay/status"), timeout=60) as r: + st = json.loads(r.read().decode()) + print("PUBLIC auto=", (st.get("settings") or {}).get("youtube_relay_enabled")) + for lane in st.get("lanes") or []: + if "nomadvlog" in str(lane.get("name") or "").lower(): + print("PUBLIC lane", json.dumps({k: lane.get(k) for k in ["name","status","error","source_room_id","anchor_name","ffmpeg_pid","manual_hold","recent_log"]}, ensure_ascii=False)[:1200]) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dy_nomadvlog_diag.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_dy_nomadvlog_diag.sh", timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_nomadvlog_flap2.py b/scripts/_diag_nomadvlog_flap2.py new file mode 100644 index 0000000..4588ab2 --- /dev/null +++ b/scripts/_diag_nomadvlog_flap2.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +"""Diagnose nomadvlog flap via python sqlite on VPS.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PY = r''' +import json, time, sqlite3, datetime +DB="/opt/douyinWEB/backend/data/monitor.db" +BJ=datetime.timezone(datetime.timedelta(hours=8)) +conn=sqlite3.connect(DB) +conn.row_factory=sqlite3.Row + +def bj(ts): + try: + return datetime.datetime.fromtimestamp(float(ts or 0), BJ).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + return str(ts) + +# find group(s) +rows=conn.execute("SELECT id,name,category,enabled,neko_instance_id,youtube_channel_id FROM yt_assign_groups WHERE lower(name) LIKE '%nomadvlog%'").fetchall() +print("GROUPS", [dict(r) for r in rows]) +gids=[r["id"] for r in rows] +if not gids: + raise SystemExit("no nomadvlog group") + +# tables present +tabs={r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} +print("HAS", {t for t in tabs if "relay" in t or "event" in t or "session" in t or "kv" in t}) + +for gid in gids: + print("\n====", gid) + if "youtube_relay_state" in tabs: + st=conn.execute("SELECT * FROM youtube_relay_state WHERE group_id=?", (gid,)).fetchone() + if st: + d=dict(st) + print("STATE status=", d.get("status"), "room=", d.get("source_room_id"), "anchor=", d.get("anchor_name"), "pid=", d.get("ffmpeg_pid")) + print(" err=", (d.get("error") or "")[:200]) + print(" upd=", bj(d.get("updated_at")), "start=", bj(d.get("started_at"))) + log=d.get("recent_log") or "" + if isinstance(log, str) and log.startswith("["): + try: log=json.loads(log) + except Exception: pass + if isinstance(log, list): + print(" recent_log:") + for line in log[-40:]: + print(" ", line) + else: + print(" recent_log_raw=", str(log)[-1500:]) + # sessions for this group (youtube monitor uses room_pk=group_id) + if "sessions" in tabs: + sess=conn.execute( + """ + SELECT id,room_id,status,anchor_name,title, + started_at,ended_at,updated_at + FROM sessions + WHERE room_pk=? OR room_id LIKE ? + ORDER BY started_at DESC LIMIT 40 + """, + (gid, f"%{gid}%"), + ).fetchall() + print("SESSIONS", len(sess)) + for s in sess: + print(" ", bj(s["started_at"]), "->", bj(s["ended_at"] or 0), "st=", s["status"], "room=", s["room_id"], "title=", (s["title"] or "")[:50]) + +# events +print("\n==== EVENTS 24h nomadvlog / YouTube 开停播 ====") +ev=conn.execute( + """ + SELECT created_at, kind, level, message, room_id, room_pk, session_id + FROM events + WHERE created_at > ? + AND ( + message LIKE '%nomadvlog%' + OR message LIKE '%YouTube 开播%' + OR message LIKE '%YouTube 停播%' + OR room_pk IN ({}) + ) + ORDER BY created_at DESC LIMIT 120 + """.format(",".join("?"*len(gids))), + (time.time()-24*3600, *gids), +).fetchall() +for e in ev: + print(bj(e["created_at"]), e["kind"], (e["message"] or "")[:130]) + +# count flaps last 24h +opens=sum(1 for e in ev if "开播" in (e["message"] or "") and "nomadvlog" in (e["message"] or "").lower()) +# also by room_pk +opens2=sum(1 for e in ev if "开播" in (e["message"] or "") and e["room_pk"] in gids) +closes=sum(1 for e in ev if "停播" in (e["message"] or "") and (e["room_pk"] in gids or "nomadvlog" in (e["message"] or "").lower())) +print("FLAP_COUNT open_by_name", opens, "open_by_pk", opens2, "close", closes) + +# settings +print("\n==== SETTINGS ====") +for k in ["youtube_relay_enabled","youtube_relay_time_slot_mode","youtube_relay_exclusive_live","youtube_relay_respect_schedule","youtube_relay_on_air_deadline_sec"]: + # try kv_settings and settings + row=None + if "kv_settings" in tabs: + row=conn.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone() + if not row and "settings" in tabs: + row=conn.execute("SELECT value FROM settings WHERE key=?", (k,)).fetchone() + print(k, row["value"] if row else None) + +# schedule +print("\n==== SCHEDULE ====") +import sys +sys.path.insert(0,"/opt/douyinWEB/backend") +from app import yt_assign_db +sched=yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) +print("now keys", list(sched.keys())[:20]) +for c in (sched.get("channels") or []): + name=str(c.get("name") or "") + if "nomadvlog" in name.lower() or c.get("active"): + print(json.dumps({k:c.get(k) for k in c.keys() if k in ("name","active","group_id","alias_group_ids","window_label","slot_label","start","end","window","label","begin","finish","from","to") or "slot" in k or "window" in k or "time" in k}, ensure_ascii=False)) + +conn.close() +''' + +REMOTE = r"""#!/bin/bash +set -e +cat > /tmp/_dy_nv_diag.py <<'EOF' +""" + PY + r""" +EOF +/opt/douyinWEB/backend/.venv/bin/python /tmp/_dy_nv_diag.py +echo "=== JOURNAL ===" +journalctl -u douyinweb-api.service --since '24 hours ago' --no-pager 2>/dev/null | grep -iE 'nomadvlog|45f9bd79|source_switch|outside_slot|invalid push|on_air|halt_session|exclusive' | tail -150 || true +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dy_nv_remote.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_dy_nv_remote.sh", timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_nomadvlog_gid.py b/scripts/_diag_nomadvlog_gid.py new file mode 100644 index 0000000..fe71b75 --- /dev/null +++ b/scripts/_diag_nomadvlog_gid.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import sqlite3, datetime, json +from collections import Counter +BJ=datetime.timezone(datetime.timedelta(hours=8)) +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +gid='45f9bd79-2039-4985-8176-5e41b014281b' +g=con.execute('SELECT id,name,neko_instance_id,ops_neko_slot,neko_open_prefer,ops_neko_open_url,neko_enabled FROM yt_assign_groups WHERE id=?',(gid,)).fetchone() +print('group', dict(g) if g else None) +rows=con.execute('SELECT * FROM yt_relay_sessions WHERE group_id=? ORDER BY started_at DESC LIMIT 100',(gid,)).fetchall() +print('n_sessions', len(rows)) +print('reasons', dict(Counter(str(r['end_reason'] or '') for r in rows))) +print('=== first 40 by time desc ===') +for r in rows[:40]: + d=dict(r) + for k in ('started_at','ended_at'): + try: d[k+'_bj']=datetime.datetime.fromtimestamp(float(d[k]),BJ).strftime('%m-%d %H:%M:%S') + except Exception: pass + meta=d.get('metadata_json') or '' + print(d.get('started_at_bj'), '->', d.get('ended_at_bj'), 'dur', d.get('duration_seconds'), 'reason', d.get('end_reason'), 'status', d.get('status'), 'room', d.get('source_room_id'), 'meta', str(meta)[:120]) +# cluster 04:00-06:00 BJ on 09-10 +print('=== 09-10 04:00-06:30 cluster ===') +cluster=[] +for r in rows: + try: + st=float(r['started_at']) + bj=datetime.datetime.fromtimestamp(st,BJ) + except Exception: + continue + if bj.month==9 and bj.day==10 and 4<=bj.hour<7: + cluster.append(r) +print('cluster_n', len(cluster)) +print('cluster_reasons', dict(Counter(str(r['end_reason'] or '') for r in cluster))) +durs=[float(r['duration_seconds'] or 0) for r in cluster] +if durs: + print('dur_min/avg/max', min(durs), sum(durs)/len(durs), max(durs)) +# studio samples for this group overnight +print('=== studio samples gid overnight ===') +samples=con.execute('SELECT * FROM yt_studio_samples WHERE group_id=? ORDER BY ts DESC LIMIT 80',(gid,)).fetchall() +print('n', len(samples)) +for s in samples[:25]: + d=dict(s) + try: d['ts_bj']=datetime.datetime.fromtimestamp(float(d['ts']),BJ).strftime('%m-%d %H:%M:%S') + except Exception: pass + print(d.get('ts_bj'), 'on_air', d.get('on_air'), 'status', d.get('live_status'), 'health', d.get('health'), 'page', d.get('live_page_open'), 'ref', d.get('neko_ref'), 'src', d.get('detect_source')) +# also count on_air=1 for this group today +n_live=con.execute('SELECT COUNT(*) FROM yt_studio_samples WHERE group_id=? AND on_air=1',(gid,)).fetchone()[0] +n_wait=con.execute('SELECT COUNT(*) FROM yt_studio_samples WHERE group_id=? AND on_air=0',(gid,)).fetchone()[0] +print('samples on_air1', n_live, 'on_air0', n_wait) +# successful long sessions earlier same push_date +print('=== longer sessions same day ===') +for r in rows: + if float(r['duration_seconds'] or 0) >= 300: + try: + sb=datetime.datetime.fromtimestamp(float(r['started_at']),BJ).strftime('%m-%d %H:%M:%S') + except Exception: + sb='?' + print(sb, 'dur', r['duration_seconds'], 'reason', r['end_reason'], 'date', r['push_date']) +st=con.execute('SELECT status,error,ffmpeg_pid,updated_at FROM yt_relay_states WHERE group_id=?',(gid,)).fetchone() +print('state', dict(st) if st else None) +# how many sessions on push_date before flap +print('=== by push_date ===') +for row in con.execute('SELECT push_date, COUNT(*), AVG(duration_seconds), SUM(CASE WHEN end_reason=\"studio_not_on_air\" THEN 1 ELSE 0 END) FROM yt_relay_sessions WHERE group_id=? GROUP BY push_date ORDER BY push_date DESC LIMIT 8',(gid,)): + print(tuple(row)) +con.close() +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command("python3 - <<'PY'\n" + REMOTE + "\nPY", timeout=60) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err: + print("STDERR", err[:2000]) +c.close() diff --git a/scripts/_diag_nomadvlog_telemetry.py b/scripts/_diag_nomadvlog_telemetry.py new file mode 100644 index 0000000..979df32 --- /dev/null +++ b/scripts/_diag_nomadvlog_telemetry.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +"""Continue: was Studio really stuck, or ops_cdp_ensure fake waiting?""" +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import sqlite3, datetime, json +from collections import Counter +BJ=datetime.timezone(datetime.timedelta(hours=8)) +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +gid='45f9bd79-2039-4985-8176-5e41b014281b' +# samples during flap window 04:48-05:30 BJ 09-10 +print('=== detect_source during flap ===') +rows=[] +for s in con.execute('SELECT * FROM yt_studio_samples WHERE group_id=? ORDER BY ts DESC LIMIT 500',(gid,)): + d=dict(s) + try: + bj=datetime.datetime.fromtimestamp(float(d['ts']),BJ) + except Exception: + continue + if bj.month==9 and bj.day==10 and ((bj.hour==4 and bj.minute>=40) or (bj.hour==5 and bj.minute<=40)): + rows.append(d) +print('n', len(rows)) +print('sources', dict(Counter(str(r.get('detect_source') or '') for r in rows))) +print('on_air', dict(Counter(int(r.get('on_air') or 0) for r in rows))) +print('live_status', dict(Counter(str(r.get('live_status') or '') for r in rows))) +print('--- sample lines ---') +for d in sorted(rows, key=lambda x: float(x['ts']))[:15]: + bj=datetime.datetime.fromtimestamp(float(d['ts']),BJ).strftime('%H:%M:%S') + print(bj, 'src', d.get('detect_source'), 'on_air', d.get('on_air'), 'st', d.get('live_status'), 'ref', d.get('neko_ref'), 'meta', str(d.get('meta_json') or '')[:80]) +print('--- last 10 in window ---') +for d in sorted(rows, key=lambda x: float(x['ts']))[-10:]: + bj=datetime.datetime.fromtimestamp(float(d['ts']),BJ).strftime('%H:%M:%S') + print(bj, 'src', d.get('detect_source'), 'on_air', d.get('on_air'), 'st', d.get('live_status'), 'ref', d.get('neko_ref')) + +# Sept 9 morning success window samples +print('=== 09-09 04:50-06:00 samples ===') +rows2=[] +for s in con.execute('SELECT * FROM yt_studio_samples WHERE group_id=? ORDER BY ts DESC LIMIT 2000',(gid,)): + d=dict(s) + try: + bj=datetime.datetime.fromtimestamp(float(d['ts']),BJ) + except Exception: + continue + if bj.month==9 and bj.day==9 and bj.hour in (4,5,6,7,8,9): + rows2.append(d) +print('n', len(rows2)) +print('sources', dict(Counter(str(r.get('detect_source') or '') for r in rows2))) +print('on_air', dict(Counter(int(r.get('on_air') or 0) for r in rows2))) +print('live_status', dict(Counter(str(r.get('live_status') or '') for r in rows2))) + +# any meta mentioning daily/limit/stream +print('=== meta with limit/daily ===') +n=0 +for s in con.execute('SELECT ts,detect_source,on_air,live_status,meta_json FROM yt_studio_samples WHERE group_id=? ORDER BY ts DESC LIMIT 3000',(gid,)): + meta=str(s['meta_json'] or '').lower() + if 'limit' in meta or 'daily' in meta or 'quota' in meta: + bj=datetime.datetime.fromtimestamp(float(s['ts']),BJ).strftime('%m-%d %H:%M:%S') + print(bj, s['detect_source'], s['on_air'], s['live_status'], meta[:200]) + n+=1 + if n>=20: break +print('limit_hits', n) + +# FFmpeg: did sessions actually get frames? check metadata +print('=== session meta keys during flap ===') +for r in con.execute('SELECT started_at,ended_at,duration_seconds,metadata_json FROM yt_relay_sessions WHERE group_id=? ORDER BY started_at DESC LIMIT 5',(gid,)): + try: + bj=datetime.datetime.fromtimestamp(float(r['started_at']),BJ).strftime('%H:%M:%S') + except Exception: + bj='?' + meta=r['metadata_json'] or '{}' + try: + m=json.loads(meta) + except Exception: + m={} + print(bj, 'dur', round(float(r['duration_seconds'] or 0),1), 'keys', list(m.keys())[:12], 'err', str(m.get('error') or m.get('last_error') or '')[:100]) +con.close() +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command("python3 - <<'PY'\n" + REMOTE + "\nPY", timeout=90) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err: + print("STDERR", err[:1500]) +c.close() diff --git a/scripts/_diag_nomadvlog_why_pending.py b/scripts/_diag_nomadvlog_why_pending.py new file mode 100644 index 0000000..b3e02d3 --- /dev/null +++ b/scripts/_diag_nomadvlog_why_pending.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +import datetime +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +BJ = datetime.timezone(datetime.timedelta(hours=8)) + +REMOTE = r''' +import sqlite3, datetime +BJ=datetime.timezone(datetime.timedelta(hours=8)) +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +g=con.execute("SELECT id,name,neko_instance_id,neko_enabled FROM yt_assign_groups WHERE lower(name) LIKE '%nomad%'").fetchall() +print('groups', [dict(x) for x in g]) +gid=str(g[0]['id']) if g else '' +print('gid', gid) +cols=[x[1] for x in con.execute('PRAGMA table_info(yt_relay_sessions)')] +print('sess_cols', cols) +rows=con.execute('SELECT * FROM yt_relay_sessions WHERE group_id=? ORDER BY started_at DESC LIMIT 60',(gid,)).fetchall() +print('=== sessions ===') +for r in rows: + d=dict(r) + for k in list(d): + if 'at' in k or k in ('started_at','ended_at','created_at'): + try: + d[k+'_bj']=datetime.datetime.fromtimestamp(float(d[k]),BJ).strftime('%m-%d %H:%M:%S') + except Exception: + pass + keys=['id','started_at_bj','ended_at_bj','end_reason','status','source_room_id','error'] + print({k:d.get(k) for k in keys if k in d or d.get(k) is not None}) +# earliest studio_not_on_air cluster +print('=== count by end_reason last 80 ===') +from collections import Counter +c=Counter(str(dict(r).get('end_reason') or '') for r in rows) +print(dict(c)) +# relay state + last error +st=con.execute('SELECT * FROM yt_relay_states WHERE group_id=?',(gid,)).fetchone() +if st: + d=dict(st) + print('state', {k:d.get(k) for k in ('status','error','ffmpeg_pid','source_room_id','updated_at')}) + print('recent_log', (d.get('recent_log') or '')[:800]) +# studio samples +try: + sc=[x[1] for x in con.execute('PRAGMA table_info(yt_studio_samples)')] + print('sample_cols', sc) + # ops-2 often nomadvlog + samples=con.execute('SELECT * FROM yt_studio_samples ORDER BY ts DESC LIMIT 40').fetchall() + for s in samples: + d=dict(s) + try: d['ts_bj']=datetime.datetime.fromtimestamp(float(d['ts']),BJ).strftime('%m-%d %H:%M:%S') + except Exception: pass + print({k:d.get(k) for k in ('ts_bj','neko_ref','neko_kind','on_air','live_status','live_page_open','health','group_id')}) +except Exception as e: + print('no samples', e) +con.close() +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command("python3 - <<'PY'\n" + REMOTE + "\nPY", timeout=60) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err: + print("STDERR", err) +c.close() diff --git a/scripts/_diag_opsneko_black.py b/scripts/_diag_opsneko_black.py new file mode 100644 index 0000000..cfb064e --- /dev/null +++ b/scripts/_diag_opsneko_black.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose ops-neko black screen / no Chrome.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*PHYS[:3], password=PHYS[3], timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + print( + run( + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set -e +echo === ps chrome/neko === +docker exec douyinweb-ops-neko-1 bash -lc "ps aux | grep -E \"chrome|chromium|neko|Xvfb|openbox|supervis\" | grep -v grep | head -40" || true +echo === supervisor === +docker exec douyinweb-ops-neko-1 bash -lc "ls -la /etc/neko/supervisord/ /etc/neko/browser-launch.sh 2>&1; head -40 /etc/neko/supervisord/*.conf 2>&1 | head -60" || true +echo === browser-launch === +docker exec douyinweb-ops-neko-1 bash -lc "ls -la /etc/neko/browser-launch.sh; head -5 /etc/neko/browser-launch.sh; file /etc/neko/browser-launch.sh" || true +echo === env key === +docker exec douyinweb-ops-neko-1 env | grep -E "NEKO_|DISPLAY|PROXY" | sort +echo === logs tail === +docker logs --tail 80 douyinweb-ops-neko-1 2>&1 | tail -80 +echo === compare assign neko1 === +docker ps -a --filter name=douyinweb-neko-1 --format "{{.Names}} {{.Status}}" +docker exec douyinweb-neko-1 bash -lc "ps aux | grep -E \"chrome|Xvfb\" | grep -v grep | head -10" 2>/dev/null || echo assign_neko1_no_chrome_or_down +echo === compose snippet ops === +head -80 /opt/douyinWEB/backend/data/ops_neko/docker-compose.yml 2>/dev/null | head -80 +' +""" + ), + flush=True, + ) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_loading.py b/scripts/_diag_opsneko_loading.py new file mode 100644 index 0000000..79b3889 --- /dev/null +++ b/scripts/_diag_opsneko_loading.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose ops-neko/1 stuck loading (HTTP ok vs WebRTC).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def ssh(spec): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(spec[0], spec[1], spec[2], spec[3], timeout=40, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=60): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def main(): + p = ssh(PHYS) + print("=== PHYS ops-neko-1 ===", flush=True) + print( + run( + p, + "echo '4669805' | sudo -S -p '' bash -lc '" + "docker ps -a --filter name=douyinweb-ops-neko-1 --format \"{{.Names}} {{.Status}} {{.Ports}}\"; " + "echo ---env---; " + "docker inspect douyinweb-ops-neko-1 --format \"{{range .Config.Env}}{{println .}}{{end}}\" 2>/dev/null | " + " grep -E \"NEKO_WEBRTC|NEKO_BROWSER|NEKO_START|NEKO_SERVER|NEKO_INSTANCE|NEKO_LIVE|NEKO_TAMPER|NEKO_MANAGED|NEKO_DESKTOP|NEKO_MAX|NEKO_VIDEO\" | head -40; " + "echo ---listen---; " + "ss -lntup | grep -E \"18200|62300|6250\" | head -20; " + "echo ---wg---; " + "ip -br a show wg-dy wg-dy-cn 2>/dev/null; " + "wg show wg-dy-cn latest-handshakes 2>/dev/null; " + "wg show wg-dy latest-handshakes 2>/dev/null; " + "echo ---http local---; " + "curl -sS -m 5 -o /dev/null -w \"local18200=%{http_code}\\n\" http://127.0.0.1:18200/; " + "curl -sS -m 5 -o /dev/null -w \"localws=%{http_code}\\n\" -H \"Upgrade: websocket\" -H \"Connection: Upgrade\" http://127.0.0.1:18200/ws || true; " + "echo ---api nat---; " + "grep -E \"DY_NEKO_NAT|DY_NEKO_CN|DY_PUBLIC|DY_NEKO_HTTP\" /etc/systemd/system/douyinweb-api.service 2>/dev/null | head -20; " + "'", + 90, + ), + flush=True, + ) + p.close() + + v = ssh(VPS) + print("=== VPS edge ===", flush=True) + print( + run( + v, + r""" +echo ---public http--- +curl -sS -m 12 -o /dev/null -w 'ops1=%{http_code} t=%{time_total}\n' https://dy.nomadro.com/ops-neko/1/ +curl -sS -m 12 -o /tmp/ops1.html -w 'ops1_body=%{http_code} size=%{size_download}\n' https://dy.nomadro.com/ops-neko/1/ +head -c 300 /tmp/ops1.html; echo +grep -oE 'n\.eko|neko|websocket|WebRTC' /tmp/ops1.html | head -10 +echo ---frp aux--- +systemctl is-active dy-frp-http-aux +ss -lntp | grep -E '18200|62300|28333' | head -20 +echo ---caddy ops-neko--- +grep -n 'ops-neko\|62300\|18200' /etc/caddy/sites/dy.nomadro.com.caddy | head -40 +echo ---mux from vps to guest via frp?--- +# TCP mux probe via frp if forwarded +timeout 3 bash -c 'echo >/dev/tcp/127.0.0.1/62300' && echo tcp62300_local_open || echo tcp62300_local_closed +# via wg +timeout 3 bash -c 'echo >/dev/tcp/10.8.0.2/62300' && echo tcp62300_wg_open || echo tcp62300_wg_closed +timeout 3 bash -c 'echo >/dev/tcp/10.8.0.2/18200' && echo http18200_wg_open || echo http18200_wg_closed +echo ---public nat1to1 guess--- +# what IP does assign neko use +curl -sS -m 8 https://dy.nomadro.com/api/health | head -c 200; echo +""", + 90, + ), + flush=True, + ) + + # Tencent edge if reachable + try: + t = paramiko.SSHClient() + t.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + t.connect("82.157.112.245", 22, "ubuntu", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + print("=== TENCENT ===", flush=True) + print( + run( + t, + r""" +echo ---cn ops-neko--- +curl -sS -m 12 -o /dev/null -w 'cn_ops1=%{http_code}\n' https://dy.nomadro.cn/ops-neko/1/ || true +curl -sS -m 12 -o /dev/null -w 'cn_neko1=%{http_code}\n' https://dy.nomadro.cn/neko/1/ || true +echo ---dnat mux--- +sudo iptables -t nat -S | grep -E '62300|52300|9200|18200' | head -30 +ss -lntup | grep -E '62300|52300' | head -15 +ip -br a show wg-dy-cn 2>/dev/null +ping -c1 -W2 10.9.0.2 >/dev/null && echo ping_guest_ok || echo ping_guest_fail +""", + 60, + ), + flush=True, + ) + t.close() + except Exception as exc: + print("TENCENT ssh fail", exc, flush=True) + v.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_profiles.py b/scripts/_diag_opsneko_profiles.py new file mode 100644 index 0000000..3ac7446 --- /dev/null +++ b/scripts/_diag_opsneko_profiles.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose ops-neko profile damage: Google login / cookies / backups.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +set -e +echo "===== profile dirs =====" +for i in 1 2; do + p=/opt/douyinWEB/backend/data/ops_neko/profiles/$i + echo "--- profile $i ---" + ls -la "$p/Default" 2>/dev/null | head -40 || echo MISSING + echo "size:" + du -sh "$p" "$p/Default" 2>/dev/null || true + for f in Cookies "Login Data" "Web Data" Preferences "Secure Preferences" "Network/Cookies" "Account Web Data"; do + fp="$p/Default/$f" + if [ -e "$fp" ]; then + echo "OK $f $(stat -c '%s %y' "$fp")" + else + echo "NO $f" + fi + done + # google account hints in Preferences + python3 - </dev/null | head +ls -la /opt/douyinWEB/backend/data/ops_neko/ 2>/dev/null +find /opt/douyinWEB -name '*ops_neko*bak*' 2>/dev/null | head +ls /tmp/*ops*neko* 2>/dev/null | head +ls /tmp/*profile* 2>/dev/null | head + +echo "===== current chrome tabs / urls =====" +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "--- $name ---" + docker exec "$name" python3 - <<'PY' 2>/dev/null || echo cdp_fail +import json, urllib.request +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +except Exception as e: + print("err", e); raise SystemExit +for t in tabs: + if t.get("type") in ("page","service_worker"): + print(t.get("type"), (t.get("url") or "")[:120]) +PY +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_ops_profiles.sh", "wb") as f: + f.write(SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_diag_ops_profiles.sh", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_tm.py b/scripts/_diag_opsneko_tm.py new file mode 100644 index 0000000..3afb0aa --- /dev/null +++ b/scripts/_diag_opsneko_tm.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +for i in 1 2; do + echo "===== OPS$i =====" + docker ps -a --filter name=douyinweb-ops-neko-$i --format "{{.Names}} {{.Status}}" + docker exec douyinweb-ops-neko-$i bash -lc " + echo --- chrome --- + supervisorctl status google-chrome 2>/dev/null || true + echo --- provisioning --- + curl -fsS -m 3 http://127.0.0.1:18080/tampermonkey-provisioning.json | head -c 220; echo + echo --- policies --- + ls -la /etc/opt/chrome/policies/managed/ 2>/dev/null || ls -la /etc/chromium/policies/managed/ 2>/dev/null || echo NO_POLICIES + echo --- env --- + env | grep -E \"TAMPER|MANAGED|NEKO_\" | sort + echo --- profile --- + P=\$(ls -d /home/*/.config/google-chrome/Default 2>/dev/null | head -1) + echo PROFILE=\$P + if [ -n \"\$P\" ]; then + ls \"\$P/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo\" 2>/dev/null || echo NO_TM_EXT + strings \"\$P/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo\"/* 2>/dev/null | grep -E \"YouTube Studio Auto Dismiss|auto-dismiss\" | head -5 || echo NO_SCRIPT_IN_LES + python3 -c \" +import json +from pathlib import Path +p=Path(r\\\"\$P/Preferences\\\") +d=json.loads(p.read_text()) if p.exists() else {} +e=(d.get(\\\"extensions\\\") or {}).get(\\\"settings\\\") or {} +tm=e.get(\\\"dhdgffkkebhmkfjojejmpbldmpobfkfo\\\") or {} +print(\\\"tm_state\\\", tm.get(\\\"state\\\"), \\\"path\\\", tm.get(\\\"path\\\"), \\\"disabled\\\", tm.get(\\\"disable_reasons\\\")) +\" 2>/dev/null || true + fi + " 2>&1 | head -100 +done +echo ===== HOST ASSETS ===== +ls -la /opt/douyinWEB/backend/neko/provisioning/ | head +grep -n hash /opt/douyinWEB/backend/neko/policies/policies.json | head +cd /opt/douyinWEB/backend/neko && python3 render_tampermonkey_provisioning.py 2>&1 | tail -5 +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_tm2.py b/scripts/_diag_opsneko_tm2.py new file mode 100644 index 0000000..55339e1 --- /dev/null +++ b/scripts/_diag_opsneko_tm2.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +for i in 1 2; do + echo "===== OPS$i DEEP =====" + docker exec douyinweb-ops-neko-$i bash -lc " + P=/home/neko/.config/google-chrome/Default + echo --- LES size --- + du -sh \"\$P/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo\" 2>/dev/null || echo NO_LES + echo --- Managed --- + du -sh \"\$P/Managed Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo\" 2>/dev/null || echo NO_MANAGED + echo --- grep LES --- + grep -aR -l \"YouTube Studio Auto Dismiss\" \"\$P\" 2>/dev/null | head -10 || echo NONE + echo --- grep Auto Dismiss count --- + grep -aR \"YouTube Studio Auto Dismiss\" \"\$P/Local Extension Settings\" \"\$P/Managed Extension Settings\" 2>/dev/null | wc -l + echo --- chrome log --- + grep -iE \"tamper|provision|jsonImport|userscript|557378|greasyfork|hash\" /var/log/neko/google-chrome.log 2>/dev/null | tail -40 || echo NO_LOG + echo --- browser-launch log --- + grep -iE \"tamper|repair|seed|script\" /var/log/neko/browser-launch.log 2>/dev/null | tail -30 || ls /var/log/neko/ 2>/dev/null | head + echo --- curl greasyfork via proxy --- + curl -fsS -m 8 -x http://host.docker.internal:7890 -o /dev/null -w \"%{http_code}\" https://greasyfork.org/scripts/557378-youtube-studio-auto-dismiss/code/YouTube%20Studio%20Auto%20Dismiss.user.js; echo + echo --- local provisioning script name --- + python3 -c \"import json; d=json.load(open(\\\"/var/www/provisioning/tampermonkey-provisioning.json\\\")); print(d[\\\"scripts\\\"][0].get(\\\"name\\\"), \\\"has_content\\\", bool(d[\\\"scripts\\\"][0].get(\\\"content\\\") or d[\\\"scripts\\\"][0].get(\\\"code\\\")), \\\"keys\\\", list(d[\\\"scripts\\\"][0].keys())[:12])\" + " 2>&1 +done +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=150) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_tm_cdp.py b/scripts/_diag_opsneko_tm_cdp.py new file mode 100644 index 0000000..3ca62b8 --- /dev/null +++ b/scripts/_diag_opsneko_tm_cdp.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""CDP probe: Tampermonkey tabs / Studio console / script markers on ops-neko 1+2.""" +import json +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +for i in 1 2; do + echo "===== OPS$i CDP =====" + docker exec douyinweb-ops-neko-$i python3 - <<'"'"'PY'"'"' +import json, urllib.request +def get(url, timeout=4): + with urllib.request.urlopen(url, timeout=timeout) as r: + return r.read().decode("utf-8", "replace") +try: + tabs = json.loads(get("http://127.0.0.1:9222/json/list")) +except Exception as e: + print("cdp_fail", e) + raise SystemExit(0) +print("tabs", len(tabs)) +for t in tabs: + u = t.get("url") or "" + title = (t.get("title") or "")[:60] + print("-", title, "|", u[:120]) +# Find studio or TM dashboard +junk = 0 +for t in tabs: + u = (t.get("url") or "").lower() + if "tampermonkey.net/changelog" in u or "tampermonkey.net/installed" in u: + junk += 1 + tid = t.get("id") + if tid: + try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=3) + except Exception: + pass +print("closed_junk", junk) +# Evaluate on Studio tab if any +studio = None +for t in tabs: + u = t.get("url") or "" + if "studio.youtube.com" in u and t.get("webSocketDebuggerUrl"): + studio = t + break +if not studio: + print("no_studio_tab") + raise SystemExit(0) +ws = studio.get("webSocketDebuggerUrl") +print("studio", (studio.get("url") or "")[:100]) +# Use HTTP /json/runtime/evaluate is not available; use websocket via simple HTTP endpoint if exists +# Fallback: chrome remote via /json/activate + print marker via Runtime — need websocket. +# Instead dump LES keys for enabled scripts. +import os, subprocess, re +p = "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +out = subprocess.check_output(["bash","-lc", f"strings {p}/* 2>/dev/null | grep -E \"YouTube Studio|@version|enabled|error|internal\" | head -40"], text=True, errors="replace") +print("--- LES strings ---") +print(out) +PY +done +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_opsneko_tm_ext.py b/scripts/_diag_opsneko_tm_ext.py new file mode 100644 index 0000000..f25a90b --- /dev/null +++ b/scripts/_diag_opsneko_tm_ext.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose Tampermonkey EXTENSION load errors on ops-neko 1/2.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +for i in 1 2; do + echo "===== OPS$i =====" + docker exec douyinweb-ops-neko-$i bash -lc " + P=/home/neko/.config/google-chrome/Default + EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo + echo --- Preferences TM entry --- + python3 -c \" +import json +from pathlib import Path +ext='dhdgffkkebhmkfjojejmpbldmpobfkfo' +p=Path('/home/neko/.config/google-chrome/Default/Preferences') +d=json.loads(p.read_text()) if p.exists() else {} +e=((d.get('extensions') or {}).get('settings') or {}).get(ext) or {} +print('state', e.get('state')) +print('path', e.get('path')) +print('location', e.get('location')) +mf=e.get('manifest') if isinstance(e.get('manifest'), dict) else {} +print('manifest_ver', mf.get('version')) +print('disable_reasons', e.get('disable_reasons')) +print('from_webstore', e.get('from_webstore')) +print('blacklist', e.get('blacklist')) +print('keys', sorted(e.keys())[:40]) +\" + echo --- Extension files --- + ls -la \"\$P/Extensions/\$EXT\" 2>/dev/null || echo NO_EXT_DIR + ls -la \"\$P/Extensions/\$EXT\"/*/ 2>/dev/null | head -30 || echo NO_VER + python3 -c \" +import json +from pathlib import Path +root=Path('/home/neko/.config/google-chrome/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo') +print('exists', root.exists()) +for m in root.glob('*/manifest.json'): + d=json.load(open(m)) + print('manifest', m.parent.name, 'mv', d.get('manifest_version'), 'ver', d.get('version'), 'name', d.get('name')) + # check required files + for rel in ['background.html','background.js','extension.js']: + p=m.parent/rel + print(' ', rel, 'ok' if p.exists() else 'MISSING', p.stat().st_size if p.exists() else 0) +\" + echo --- Secure Preferences --- + python3 -c \" +import json +from pathlib import Path +ext='dhdgffkkebhmkfjojejmpbldmpobfkfo' +p=Path('/home/neko/.config/google-chrome/Default/Secure Preferences') +print('exists', p.exists(), 'size', p.stat().st_size if p.exists() else 0) +if p.exists(): + d=json.loads(p.read_text()) + e=((d.get('extensions') or {}).get('settings') or {}).get(ext) or {} + print('secure_state', e.get('state'), 'path', e.get('path'), 'disable', e.get('disable_reasons')) +\" + echo --- chrome logs --- + for f in /var/log/neko/google-chrome.log /var/log/supervisor/google-chrome*.log /tmp/chrome*.log; do + [ -f \"\$f\" ] || continue + echo FILE \$f + grep -iE 'tamper|dhdgff|Failed to load|Manifest file is missing|Extension error|Could not load' \"\$f\" 2>/dev/null | tail -20 + done + ls /var/log/neko/ 2>/dev/null + echo --- CDP --- + python3 -c \" +import json,urllib.request +try: + tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read()) +except Exception as e: + print('cdp_fail',e); raise SystemExit +print('tabs',len(tabs)) +for t in tabs[:20]: + print('-',(t.get('title') or '')[:45],'|',(t.get('url') or '')[:110]) +\" + " +done +echo ===== HOST SEED ===== +ls /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/ +python3 -c " +import json +from pathlib import Path +m=next(Path('/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo').glob('*/manifest.json')) +d=json.load(open(m)) +print(m) +print('mv',d.get('manifest_version'),'ver',d.get('version')) +" +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_phys_assign_neko_login.py b/scripts/_diag_phys_assign_neko_login.py new file mode 100644 index 0000000..5d12f66 --- /dev/null +++ b/scripts/_diag_phys_assign_neko_login.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""READ-ONLY: why physical assign-neko login/TM look gone (dy.nomadro.com).""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh_phys(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +print("===== public dy.com neko =====", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for path in ("/neko/1/", "/neko/2/", "/neko/3/", "/neko/7/", "/ops-neko/1/"): + url = "https://dy.nomadro.com" + path + try: + r = cl.get(url) + print(f"{r.status_code} {url} len={len(r.content)}", flush=True) + except Exception as ex: + print(f"ERR {url} {ex}", flush=True) + +c = ssh_phys() +run( + c, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +TM=dhdgffkkebhmkfjojejmpbldmpobfkfo +P=/opt/douyinWEB/backend/data/neko/profiles +echo "--- container identity (no change) ---" +for id in 1 2 3 7 8; do + echo "== neko-$id ==" + docker inspect douyinweb-neko-$id --format "Started={{.State.StartedAt}} Restarts={{.RestartCount}} Image={{.Config.Image}}" 2>/dev/null + docker inspect douyinweb-neko-$id --format "{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}" 2>/dev/null | grep -E "profiles|tampermonkey|policies" | head -8 +done + +echo "--- profile sizes / Cookies / TM ext ---" +for id in 1 2 3 7 8; do + echo "== profile $id ==" + du -sh "$P/$id" 2>/dev/null + ls -la --time-style=long-iso "$P/$id/Default/Cookies" "$P/$id/Default/Cookies-journal" 2>/dev/null + ls -la --time-style=long-iso "$P/$id/Default/Extensions/$TM" 2>/dev/null | head -5 + ls "$P/$id/Default/Extensions/$TM" 2>/dev/null | head + # Local Extension Settings (userscripts store) + du -sh "$P/$id/Default/Local Extension Settings/$TM" 2>/dev/null + ls -la --time-style=long-iso "$P/$id/Default/Local Extension Settings/$TM" 2>/dev/null | head -8 + # Preferences mention tampermonkey? + grep -l tampermonkey "$P/$id/Default/Preferences" 2>/dev/null && echo prefs_has_tm || echo prefs_no_tm_string + # cookie db size + stat -c "%y %s %n" "$P/$id/Default/Cookies" 2>/dev/null +done + +echo "--- CDP tabs (read-only list) for neko1/3 ---" +for id in 1 3; do + echo "== CDP neko-$id ==" + docker exec douyinweb-neko-$id python3 - </dev/null | grep -iE "force-recreate|compose up|neko.*start|recreate_all|sync_for_groups" | tail -40 +' +""", +) +c.close() +print("DONE", flush=True) diff --git a/scripts/_diag_phys_neko_exts.py b/scripts/_diag_phys_neko_exts.py new file mode 100644 index 0000000..544e637 --- /dev/null +++ b/scripts/_diag_phys_neko_exts.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""READ-ONLY: Extensions dirs + google cookies count for physical assign neko.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +cmd = r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +P=/opt/douyinWEB/backend/data/neko/profiles +TM=dhdgffkkebhmkfjojejmpbldmpobfkfo +for id in 1 2 3 4 5 6 7 8; do + echo "======== profile $id ========" + echo -n "Extensions: "; ls "$P/$id/Default/Extensions" 2>/dev/null | tr "\n" " "; echo + echo -n "TM dir: "; ls -d "$P/$id/Default/Extensions/$TM" 2>/dev/null || echo MISSING + echo -n "LiveOps ext: "; ls "$P/$id/Default/Extensions" 2>/dev/null | head -5 + # sqlite cookie hosts if possible + if command -v sqlite3 >/dev/null; then + sqlite3 "$P/$id/Default/Cookies" "select host_key,name from cookies where host_key like \"%google%\" or host_key like \"%youtube%\" limit 8;" 2>/dev/null | head + echo -n "cookie_rows="; sqlite3 "$P/$id/Default/Cookies" "select count(*) from cookies;" 2>/dev/null; echo + else + echo "no sqlite3" + # file size already known + fi +done +echo "--- who listens physical 9200 ---" +ss -lntp | grep -E ":920[0-7]\b" | head +curl -sS -m 3 -o /dev/null -w "local9200=%{http_code}\n" http://127.0.0.1:9200/ +' +""" +_i, o, e = c.exec_command(cmd, timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_phys_neko_untouched.py b/scripts/_diag_phys_neko_untouched.py new file mode 100644 index 0000000..b838df5 --- /dev/null +++ b/scripts/_diag_phys_neko_untouched.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""READ-ONLY: check if physical neko containers/profiles were touched.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as ex: + print("retry", port, i, ex, flush=True) + time.sleep(3) + raise SystemExit(f"ssh {port} fail") + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +print("===== PHYSICAL (4014) READ-ONLY =====", flush=True) +p = ssh(4014, "eric", "4669805") +run( + p, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +echo "--- docker neko/ops CreatedAt / Status (no changes) ---" +docker ps -a --filter name=douyinweb-neko --filter name=douyinweb-ops-neko \ + --format "table {{.Names}}\t{{.Status}}\t{{.CreatedAt}}" +echo "--- profile mtimes (assign + ops) ---" +ls -la --time-style=long-iso /opt/douyinWEB/backend/data/neko/profiles/ 2>/dev/null | head -20 +ls -la --time-style=long-iso /opt/douyinWEB/backend/data/ops_neko/profiles/ 2>/dev/null | head -20 +echo "--- recent docker events for neko (last 2h) ---" +docker events --since 2h --until 0s --filter type=container 2>/dev/null | grep -iE "neko|ops-neko" | tail -40 +echo "--- last journal docker/api touching neko ---" +journalctl -u douyinweb-api --since "2 hours ago" --no-pager 2>/dev/null | grep -iE "neko|force-recreate|compose" | tail -30 +echo "--- container start times ---" +for c in douyinweb-ops-neko-1 douyinweb-ops-neko-2 douyinweb-neko-1 douyinweb-neko-3; do + echo "== $c ==" + docker inspect "$c" --format "StartedAt={{.State.StartedAt}} FinishedAt={{.State.FinishedAt}} Running={{.State.Running}} RestartCount={{.RestartCount}}" 2>/dev/null +done +' +""", +) +p.close() + +print("===== VPS: confirm we only touched VPS neko =====", flush=True) +v = ssh(22, "root", "Xiao4669805") +run( + v, + r""" +set +e +echo '--- VPS local neko ---' +docker ps -a --filter name=douyinweb-neko --format 'table {{.Names}}\t{{.Status}}\t{{.CreatedAt}}\t{{.Ports}}' | head -20 +echo '--- frp-aux (remapped 1920x) ---' +systemctl is-active dy-frp-http-aux +grep -oE '1920[0-7]|920[0-7]' /etc/systemd/system/dy-frp-http-aux.service | sort | uniq -c +echo '--- dy.com neko1 upstream ---' +grep -A2 'handle_path /neko/1/\*' /etc/caddy/sites/dy.nomadro.com.caddy | head -5 +""", +) +v.close() +print("DONE", flush=True) diff --git a/scripts/_diag_quota_progress_facts.py b/scripts/_diag_quota_progress_facts.py new file mode 100644 index 0000000..c66d612 --- /dev/null +++ b/scripts/_diag_quota_progress_facts.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare yt-long board used vs uploaded + Google quota facts on dy/dylive.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] + +REMOTE = r''' +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +import json +from app import db, yt_long_db +from app.shorts_yt_quota import quota_budgets_by_profile, yt_daily_limit, _load_quota_map +from app.timeutil import push_date_from_ts, pacific_day_from_ts +import time + +cfg = db.get_settings_map() +day = push_date_from_ts(time.time()) +print("bj_day", day, "pt_day", pacific_day_from_ts(time.time())) +print("shorts_yt_daily_upload_limit", cfg.get("shorts_yt_daily_upload_limit"), "fn", yt_daily_limit(cfg)) +print("yt_long_daily_max", cfg.get("yt_long_daily_max"), "channel_daily", cfg.get("yt_long_channel_daily_max")) +print("limited_day", cfg.get("yt_long_quota_limited_day"), "reason", str(cfg.get("yt_long_quota_limited_reason") or "")[:180]) +print("quota_map", json.dumps(_load_quota_map(cfg), ensure_ascii=False)[:900]) +print("budgets", json.dumps(quota_budgets_by_profile(cfg), ensure_ascii=False)[:1500]) +board = yt_long_db.channel_board(day) +chs = board.get("channels") or [] +print("yt_long_channels", len(chs), "upload_used", yt_long_db.yt_long_upload_used(day), "daily_max", yt_long_db.yt_long_daily_max(cfg)) +weird = [] +for c in chs: + u, up, dmax = int(c.get("used") or 0), int(c.get("uploaded") or 0), int(c.get("daily_max") or 0) + if u != up or (c.get("enabled") and (u or up)): + weird.append((c.get("name"), "used", u, "uploaded", up, "sched", c.get("scheduled"), "pend", c.get("pending"), "dmax", dmax, "en", c.get("enabled"))) +print("nonzero_or_mismatch", len(weird)) +for row in weird[:20]: + print(" ", row) +s = db.shorts_channels_quota_summary(day) +print("shorts_n", len(s), "uploaded_sum", sum(int(r.get("uploaded") or 0) for r in s), "used_sum", sum(int(r.get("used") or 0) for r in s)) +# show statuses that count as used for yt-long +from app.yt_long_db import _UPLOAD_STATUSES +print("YT_LONG_UPLOAD_STATUSES", _UPLOAD_STATUSES) +PY +''' + + +def run(host: str) -> str: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", PASS, timeout=35, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2) + else: + return "ssh_fail" + _, o, e = c.exec_command(REMOTE, timeout=70) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +for label, host in HOSTS: + print(f"\n==== {label} {host} ====", flush=True) + print(run(host), flush=True) diff --git a/scripts/_diag_s3_avatars_api.py b/scripts/_diag_s3_avatars_api.py new file mode 100644 index 0000000..8478929 --- /dev/null +++ b/scripts/_diag_s3_avatars_api.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Avatar URLs + live API cover fields + dy Seaweed identity / anonymous GET.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.error +import urllib.request +from http.cookiejar import CookieJar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def http_get(url: str, headers=None, cookiejar=None): + opener = urllib.request.build_opener( + urllib.request.HTTPSHandler(context=CTX), + urllib.request.HTTPCookieProcessor(cookiejar or CookieJar()), + ) + req = urllib.request.Request(url, headers=headers or {"User-Agent": "diag"}) + with opener.open(req, timeout=25) as r: + return r.status, r.read(), dict(r.headers) + + +SCRIPT = r""" +set +e +cd /opt/douyinWEB/backend +echo '=== avatar_url samples ===' +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + for r in conn.execute("SELECT id, substr(avatar_url,1,180) FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url!='' LIMIT 8").fetchall(): + print('avatar', r[0], r[1]) + # how many http avatars + n=conn.execute("SELECT COUNT(*) FROM rooms WHERE avatar_url LIKE 'http%'").fetchone()[0] + print('http_avatars', n) + # cover_path host distribution + for r in conn.execute("SELECT CASE WHEN cover_path LIKE 'https://s3.nomadro.com%' THEN 's3.nomadro' WHEN cover_path LIKE 'https://dy.nomadro.live%' THEN 'dy.live' WHEN cover_path LIKE 'http%' THEN 'other_http' ELSE 'local' END AS k, COUNT(*) FROM sessions WHERE cover_path IS NOT NULL AND cover_path!='' GROUP BY 1").fetchall(): + print('cover_host', r[0], r[1]) +PY +echo +echo '=== seaweed identity / config ===' +ls /etc/seaweed* /var/lib/seaweed* /opt/seaweed* 2>/dev/null | head +systemctl cat seaweed-s3.service douyinweb-s3.service 2>/dev/null | head -80 +# find identity.json / config.json +find /etc /var/lib /opt /root -name '*identity*' 2>/dev/null | head -20 +find /etc /var/lib /opt -path '*seaweed*' -name '*.json' 2>/dev/null | head -30 +echo +echo '=== anonymous GET local s3 object ===' +# pick a key +KEY=$(cd /opt/douyinWEB/backend && ./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + r=conn.execute("SELECT cover_path FROM sessions WHERE cover_path LIKE '%/covers/%' ORDER BY rowid DESC LIMIT 1").fetchone() + print((r[0] if r else '').split('/douyin-covers/',1)[-1] if r else '') +PY +) +echo key_path=$KEY +curl -sS -m 5 -o /dev/null -w "anon_local_8333:%{http_code}\n" "http://127.0.0.1:8333/douyin-covers/$KEY" +curl -sS -m 5 -o /dev/null -w "anon_local_8333_root:%{http_code}\n" "http://127.0.0.1:8333/$KEY" +# with AWS style path +curl -sS -m 5 -D- -o /tmp/s3obj.bin "http://127.0.0.1:8333/douyin-covers/$(echo $KEY | sed 's#^covers/##;s#^#covers/#')" 2>&1 | head -20 +file /tmp/s3obj.bin 2>/dev/null | head -1 +echo +echo '=== frp 28333 on this host? ===' +ss -lntp | grep -E '28333|8333' | head +echo HOST_DONE +""" + +for label, host, site in [ + ("dylive", "107.173.30.245", "https://dylive.nomadro.com"), + ("dy", "108.174.50.68", "https://dy.nomadro.live"), +]: + print(f"\n######## {label} {host} ########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + break + except Exception as e: + print("retry", e, flush=True) + time.sleep(2) + else: + raise SystemExit("ssh fail") + _i, o, e = c.exec_command(SCRIPT, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + # login + fetch sessions/active sample cover fields + print(f"--- API sessions cover fields {site} ---", flush=True) + cj = CookieJar() + opener = urllib.request.build_opener( + urllib.request.HTTPSHandler(context=CTX), + urllib.request.HTTPCookieProcessor(cj), + ) + login_body = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + site + "/api/auth/login", + data=login_body, + headers={"Content-Type": "application/json", "User-Agent": "diag"}, + method="POST", + ) + try: + with opener.open(req, timeout=25) as r: + print("login", r.status, flush=True) + except Exception as ex: + print("login_err", ex, flush=True) + continue + for path in ("/api/sessions/active", "/api/rooms"): + try: + req2 = urllib.request.Request(site + path, headers={"User-Agent": "diag"}) + with opener.open(req2, timeout=30) as r: + data = json.loads(r.read().decode("utf-8", "replace")) + items = data.get("sessions") or data.get("rooms") or data.get("items") or data + if isinstance(items, dict): + items = items.get("sessions") or items.get("rooms") or [] + if not isinstance(items, list): + print(path, "unexpected", type(items), flush=True) + continue + print(path, "count", len(items), flush=True) + for it in items[:5]: + print( + " sample", + { + "id": str(it.get("id") or "")[:12], + "cover_url": (it.get("cover_url") or "")[:100], + "cover_proxy_url": (it.get("cover_proxy_url") or "")[:80], + "avatar_url": (it.get("avatar_url") or "")[:100], + "cover_path": (it.get("cover_path") or "")[:100], + }, + flush=True, + ) + except Exception as ex: + print(path, "ERR", ex, flush=True) + +# VPS: check dy.nomadro.live caddy target 28333 and probe +print("\n######## VPS caddy dy.nomadro.live S3 path ########", flush=True) +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) +_i, o, e = c.exec_command( + r""" +set +e +echo '=== active dy.nomadro.live site snippet ===' +# prefer live domain file if any +ls /etc/caddy/sites/ | grep -i dy +sed -n '1,80p;560,590p' /etc/caddy/sites/dy.nomadro.com.caddy 2>/dev/null +echo +# is there dy.nomadro.live site? +grep -Rnl 'dy.nomadro.live' /etc/caddy/sites 2>/dev/null | head +for f in /etc/caddy/sites/*live*; do echo FILE=$f; grep -nE 'douyin-covers|8333|28333|covers' "$f" 2>/dev/null | head -20; done +echo +echo '=== local 28333 ===' +ss -lntp | grep 28333 || true +curl -sS -m 5 -o /dev/null -w "vps_28333:%{http_code}\n" "http://127.0.0.1:28333/" +curl -sS -m 5 -o /dev/null -w "obj28333:%{http_code}\n" "http://127.0.0.1:28333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg" +curl -sS -m 5 -o /dev/null -w "obj_wg_dy:%{http_code}\n" "http://10.8.0.2:8333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg" +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_s3_frp_config.py b/scripts/_diag_s3_frp_config.py new file mode 100644 index 0000000..c5be3d3 --- /dev/null +++ b/scripts/_diag_s3_frp_config.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Check FRP S3 tunnel + seaweed public config (read-only).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def run(host, script): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + break + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2) + else: + raise SystemExit(f"ssh fail {host}") + _i, o, e = c.exec_command(script, timeout=60) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +print("=== VPS FRP / s3.json ===", flush=True) +print( + run( + "107.173.30.245", + r""" +set +e +systemctl is-active dy-frp-http-aux.service frpp.service +systemctl status dy-frp-http-aux.service --no-pager -l 2>&1 | head -40 +ss -lntp | grep -E '28333|18333|8333' | head +echo '--- s3.json (redact secrets) ---' +python3 - <<'PY' +import json +p='/etc/seaweedfs/s3.json' +d=json.load(open(p)) +# redact +def scrub(x): + if isinstance(x, dict): + return {k:('***' if 'secret' in k.lower() or k.lower() in ('secretkey','secret_key') else scrub(v)) for k,v in x.items()} + if isinstance(x, list): + return [scrub(i) for i in x] + return x +print(json.dumps(scrub(d), indent=2)[:2500]) +PY +""", + ), + flush=True, +) + +print("=== physical dy seaweed config ===", flush=True) +print( + run( + "108.174.50.68", + r""" +set +e +systemctl is-active douyinweb-s3.service +echo '--- douyinweb-s3.json scrubbed ---' +python3 - <<'PY' +import json +p='/etc/seaweedfs/douyinweb-s3.json' +d=json.load(open(p)) +def scrub(x): + if isinstance(x, dict): + return {k:('***' if 'secret' in k.lower() or 'key'==k.lower() or k.lower().endswith('secretkey') else scrub(v)) for k,v in x.items()} + if isinstance(x, list): + return [scrub(i) for i in x] + return x +print(json.dumps(scrub(d), indent=2)[:3000]) +PY +echo '--- identities (secrets redacted) ---' +python3 - <<'PY' +import json +d=json.load(open('/etc/seaweedfs/douyinweb-s3.json')) +for ident in d.get('identities') or []: + name=ident.get('name') + creds=ident.get('credentials') or [] + for c in creds: + ak=(c.get('accessKey') or '') + sk=(c.get('secretKey') or '') + print('identity', name, 'ak', ak[:4]+'***' if ak else '', 'sk_len', len(sk)) + for a in ident.get('actions') or []: + print(' action', a) +print('buckets', [b.get('name') for b in (d.get('buckets') or [])]) +PY +# check frpc for 8333 +grep -RniE '8333|28333|s3' /etc/frp* /opt/frp* /etc/frpp* 2>/dev/null | head -40 +ps aux | grep -iE 'frpc|frp' | grep -v grep | head +""", + ), + flush=True, +) +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_s3_public_urls.py b/scripts/_diag_s3_public_urls.py new file mode 100644 index 0000000..ecdb813 --- /dev/null +++ b/scripts/_diag_s3_public_urls.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Probe public S3 image URLs + why DY_S3_ENABLED not applied in process.""" +from __future__ import annotations + +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + +URLS = [ + "https://s3.nomadro.com/douyin-covers/covers/b9197cd9-b9af-432f-8e2a-880370ce75da.jpg", + "https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg", + "https://dylive.nomadro.com/douyin-covers/covers/b9197cd9-b9af-432f-8e2a-880370ce75da.jpg", +] + +for url in URLS: + t0 = time.time() + try: + req = urllib.request.Request(url, method="GET", headers={"User-Agent": "diag"}) + with urllib.request.urlopen(req, timeout=20, context=CTX) as r: + data = r.read(32) + print(f"OK {r.status} t={time.time()-t0:.2f}s ct={r.headers.get('content-type')} len32={len(data)} {url}", flush=True) + except urllib.error.HTTPError as e: + body = e.read()[:120] + print(f"HTTP {e.code} t={time.time()-t0:.2f}s {url} body={body!r}", flush=True) + except Exception as ex: + print(f"ERR t={time.time()-t0:.2f}s {url} {ex}", flush=True) + + +SCRIPT = r""" +set +e +echo '=== process env for API pid ===' +PID=$(ss -lntp | awk '/:8014/ {match($0,/pid=[0-9]+/); print substr($0,RSTART+4,RLENGTH-4); exit}') +echo pid=$PID +if [ -n "$PID" ]; then + tr '\0' '\n' < /proc/$PID/environ 2>/dev/null | grep -E '^(DY_S3_|DY_PUBLIC|S3_)' | sed -E 's/(SECRET_KEY=).*/\1***/' +fi +echo +echo '=== pydantic settings load test ===' +cd /opt/douyinWEB/backend +# with systemd env simulated +export DY_S3_ENABLED=true +export DY_S3_ENDPOINT=http://127.0.0.1:8333 +export DY_S3_PUBLIC_BASE=https://s3.nomadro.com +./.venv/bin/python - <<'PY' +import os +print('env DY_S3_ENABLED=', os.environ.get('DY_S3_ENABLED')) +from app.config import settings +print('settings.s3_enabled=', settings.s3_enabled, type(settings.s3_enabled)) +print('settings.s3_public_base=', settings.s3_public_base) +print('model_config=', getattr(settings, 'model_config', None) or getattr(settings, 'Config', None)) +PY +echo +echo '=== caddy s3 routes ===' +grep -RniE 's3\.nomadro|8333|douyin-covers|/covers' /etc/caddy /etc/Caddyfile /opt/caddy 2>/dev/null | head -40 +ls /etc/caddy/ 2>/dev/null +echo HOST_DONE +""" + +for label, host in [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")]: + print(f"\n######## {label} {host} ########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + break + except Exception as e: + print("retry", e, flush=True) + time.sleep(2) + else: + raise SystemExit("ssh fail") + _i, o, e = c.exec_command(SCRIPT, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_diag_shellcrash_ui.py b/scripts/_diag_shellcrash_ui.py new file mode 100644 index 0000000..bebdd0a --- /dev/null +++ b/scripts/_diag_shellcrash_ui.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Diagnose ShellCrash /ui on dy.nomadro.com. Live flush.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, port, user, pw, timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=60): + print(f"$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## public /ui", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for u in [ + "https://dy.nomadro.com/ui/", + "https://dy.nomadro.com/ui", + "https://dy.nomadro.com/ui/#/setup", + "https://dy.nomadro.cn/ui/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code} ctype={r.headers.get('content-type','')[:40]} " + f"loc={r.headers.get('location','')[:60]} body={r.text[:80]!r}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("## caddy /ui rules", flush=True) +v = connect(22) +run( + v, + "grep -nE 'ui|9999|9090|zash|shellcrash|yacd|metacubex' /etc/caddy/sites/dy.nomadro.com.caddy | head -40; " + "echo ---; " + "grep -nE 'reverse_proxy 10\\.8\\.0\\.2|reverse_proxy 127\\.0\\.0\\.1' /etc/caddy/sites/dy.nomadro.com.caddy | " + "grep -E '9999|9090|ui|4015|8014' | head -30", +) +v.close() + +print("## guest shellcrash listen", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "ss -lntp | grep -E \":(9999|9090|9091|7888|8080|6170)\\b\" || true; " + "ps aux | grep -iE \"[s]hellcrash|[m]ihomo|[c]lash|sing-box|zash\" | head -15; " + "curl -sS -m 5 -o /dev/null -w local9999=%{http_code}\\\\n http://127.0.0.1:9999/; " + "curl -sS -m 5 -o /dev/null -w local9999ui=%{http_code}\\\\n http://127.0.0.1:9999/ui/; " + "curl -sS -m 5 -o /dev/null -w local9090=%{http_code}\\\\n http://127.0.0.1:9090/; " + "ls /etc/ShellCrash /root/ShellCrash /opt/ShellCrash 2>/dev/null; " + "systemctl list-units --type=service --all | grep -iE \"shell|clash|mihomo|sing\" | head -20" + "'", + t=50, +) +g.close() + +print("## vps frp-aux listens related", flush=True) +v = connect(22) +run( + v, + "ss -lntp | grep -E ':(9999|9090|18014|14015)\\b' || true; " + "systemctl cat dy-frp-http-aux.service | head -40; " + "curl -sS -m 5 -o /dev/null -w vps9999=%{http_code}\\\\n http://127.0.0.1:9999/ui/ || true; " + "curl -sS -m 5 -o /dev/null -w via_wg9999=%{http_code}\\\\n http://10.8.0.2:9999/ui/ || true", + t=30, +) +v.close() +print("DONE", flush=True) diff --git a/scripts/_diag_shorts_claim_block.py b/scripts/_diag_shorts_claim_block.py new file mode 100644 index 0000000..2685d1a --- /dev/null +++ b/scripts/_diag_shorts_claim_block.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +"""Why claim_due returns nothing while 64 scheduled are due.""" +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +python3 <<'PY' +import sqlite3, time, os +from pathlib import Path +conn=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +conn.row_factory=sqlite3.Row +day='2026-09-09' +now=time.time() +rows=conn.execute(""" +SELECT j.id,j.status,j.channel_pk,j.upload_at,j.clip_path,j.youtube_video_id,j.error, + c.name,c.enabled,c.oauth_profile_id +FROM shorts_jobs j +LEFT JOIN shorts_channels c ON c.id=j.channel_pk +WHERE j.push_date=? AND j.status IN ('scheduled','recorded') +ORDER BY j.upload_at ASC LIMIT 20 +""",(day,)).fetchall() +print('sample due-ish') +for r in rows: + clip=str(r['clip_path'] or '') + exists=bool(clip) and Path(clip).is_file() + print(f" {r['status']} due={float(r['upload_at'] or 0)<=now} clip_ok={exists} en={r['enabled']} vid={bool(r['youtube_video_id'])} name={r['name']} path={clip[-40:] if clip else ''}") + +# claim eligibility counts +elig=conn.execute(""" +SELECT COUNT(*) c FROM shorts_jobs j +INNER JOIN shorts_channels c ON c.id=j.channel_pk +WHERE j.push_date=? AND j.status='scheduled' AND c.enabled=1 + AND j.clip_path!='' AND j.youtube_video_id='' AND j.upload_at>0 AND j.upload_at<=? +""",(day,now)).fetchone()['c'] +print('claim_eligible_scheduled', elig) + +# per channel last upload + gap +chs=conn.execute('SELECT id,name FROM shorts_channels WHERE enabled=1').fetchall() +blocked=0 +ok=0 +for ch in chs: + last=conn.execute(""" + SELECT status, finished_at, updated_at, upload_at FROM shorts_jobs + WHERE channel_pk=? AND push_date=? AND status IN ('uploading','uploaded','done') + ORDER BY COALESCE(NULLIF(finished_at,0), updated_at) DESC LIMIT 1 + """,(ch['id'],day)).fetchone() + last_ts=0 + if last: + st=last['status'] + if st in ('uploaded','done'): + last_ts=float(last['finished_at'] or last['updated_at'] or 0) + else: + last_ts=float(last['updated_at'] or last['upload_at'] or 0) + gap=now-last_ts if last_ts else 9999 + due_ch=conn.execute(""" + SELECT COUNT(*) c FROM shorts_jobs j + WHERE channel_pk=? AND push_date=? AND status IN ('scheduled','recorded') + AND clip_path!='' AND upload_at<=? AND youtube_video_id='' + """,(ch['id'],day,now)).fetchone()['c'] + if due_ch and gap<600: + blocked+=1 + print(f"GAP_BLOCK {ch['name']} gap={int(gap)}s due={due_ch} last_ts={last_ts}") + elif due_ch: + ok+=1 + print(f"READY {ch['name']} gap={int(gap)}s due={due_ch}") +print('channels_ready', ok, 'channels_gap_blocked', blocked) + +# auto upload setting +for k in ('shorts_auto_upload','shorts_enabled','shorts_upload_max_concurrent'): + r=conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone() + print('kv',k, r['value'] if r else None) + +# pipeline process +import subprocess +print(subprocess.getoutput('systemctl is-active douyinweb-api; ps aux | grep -E "[u]vicorn|[s]horts" | head -5')) +# try claim in-process +import sys +sys.path.insert(0,'/opt/douyinWEB/backend') +os.chdir('/opt/douyinWEB/backend') +from app import db +j=db.claim_due_shorts_upload() +print('claim_result', (j or {}).get('id'), (j or {}).get('status'), (j or {}).get('channel_pk')) +if j: + # roll back? leave as uploading — worker should pick; or revert + db.update_shorts_job(j['id'], status='scheduled', error='') + print('reverted to scheduled for safety') +conn.close() +PY +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command(REMOTE, timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_diag_shorts_forecast_gap.py b/scripts/_diag_shorts_forecast_gap.py new file mode 100644 index 0000000..331cade --- /dev/null +++ b/scripts/_diag_shorts_forecast_gap.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +import json, http.cookiejar, urllib.request, sys +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +base = "https://dylive.nomadro.com" +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() +op.open( + urllib.request.Request( + base + "/api/auth/login", + data=data, + method="POST", + headers={"Content-Type": "application/json"}, + ), + timeout=30, +) +with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=45) as r: + st = json.loads(r.read().decode()) +board = st.get("board") or {} +print( + "enabled", st.get("enabled"), + "running", st.get("running"), + "busy", st.get("busy"), + "live", st.get("douyin_live_count"), + "err", st.get("last_error"), +) +print( + "gap", board.get("total_gap"), + "min_unmet", board.get("min_unmet"), + "min_unmet_channels", board.get("min_unmet_channels"), + "sec_left", board.get("seconds_left"), +) +print("forecast", json.dumps(board.get("quota_forecast"), ensure_ascii=False)) +with op.open(urllib.request.Request(base + "/api/shorts/schedule"), timeout=45) as r: + b = json.loads(r.read().decode()) +print("schedule gap", b.get("total_gap"), "min_unmet", b.get("min_unmet"), "sec", b.get("seconds_left")) +print("forecast2", json.dumps(b.get("quota_forecast"), ensure_ascii=False)) +chans = [c for c in (b.get("channels") or []) if c.get("enabled")] +under = [c for c in chans if not c.get("min_met")] +print("enabled", len(chans), "under", len(under)) +pipe_full = 0 +for c in under: + if int(c.get("pipeline") or 0) >= int(c.get("daily_max") or 9): + pipe_full += 1 +print("under_pipeline_full", pipe_full) +for c in under[:10]: + print( + c.get("name"), + "up", c.get("uploaded"), + "pe", c.get("pending"), + "sch", c.get("scheduled"), + "pipe", c.get("pipeline"), + "gap", c.get("gap"), + ) +# job status breakdown via jobs API +with op.open(urllib.request.Request(base + "/api/shorts/jobs?limit=1"), timeout=30) as r: + j = json.loads(r.read().decode()) +print("jobs_total_hint", j.get("total")) +# fill once dry? +req = urllib.request.Request(base + "/api/shorts/fill-quota", data=b"{}", method="POST", headers={"Content-Type": "application/json"}) +try: + with op.open(req, timeout=90) as r: + fr = json.loads(r.read().decode()) + print("fill", json.dumps(fr, ensure_ascii=False)[:800]) +except Exception as ex: + print("fill_err", ex) diff --git a/scripts/_diag_shorts_min_quota.py b/scripts/_diag_shorts_min_quota.py new file mode 100644 index 0000000..21fe968 --- /dev/null +++ b/scripts/_diag_shorts_min_quota.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +"""Diagnose dylive Shorts: why daily_min 9 not met (esp YPP).""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from datetime import datetime, timezone, timedelta + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +BJ = timezone(timedelta(hours=8)) + + +def session(base: str): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=30) + return op + + +def call(op, base, path, method="GET", body=None, timeout=60): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + base + path, + data=data, + method=method, + headers={"Content-Type": "application/json"} if body is not None else {}, + ) + with op.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +base = "https://dylive.nomadro.com" +op = session(base) +now = time.time() +print("now_bj", datetime.now(BJ).isoformat()) + +st = call(op, base, "/api/shorts/status") +board = st.get("board") or {} +print( + "enabled=", st.get("enabled"), + "busy=", st.get("busy"), + "active_up=", st.get("active_uploads"), + "active_rec=", st.get("active_records"), + "gap=", st.get("quota_gap") or board.get("total_gap"), + "min_unmet=", board.get("min_unmet"), + "ch_gap=", st.get("channel_min_gap_sec"), + "yt_blocked=", st.get("upload_quota_blocked"), + "yt_blocked_profiles=", st.get("upload_quota_blocked_profiles"), + "yt_hint=", st.get("yt_quota_exhausted_hint"), + "yt_by_profile=", st.get("yt_quota_by_profile"), + "day_progress=", board.get("day_progress"), + "seconds_left=", board.get("seconds_left"), +) + +chans = board.get("channels") or [] +print("\n=== channels under min ===") +for c in chans: + if not c.get("enabled"): + continue + if c.get("min_met"): + continue + print( + f" {c.get('name')} ypp={c.get('ypp_ok')} used={c.get('used')}/{c.get('daily_min')} " + f"up={c.get('uploaded')} sch={c.get('scheduled')} pend={c.get('pending')} " + f"behind={c.get('behind_pace')} oauth={c.get('oauth_profile_id')}" + ) + +# jobs today by status +jobs = call(op, base, "/api/shorts/jobs?limit=200") +items = jobs.get("jobs") or [] +from collections import Counter +ctr = Counter(str(j.get("status") or "") for j in items if str(j.get("push_date") or "") == str(board.get("push_date") or "")) +print("\n=== job status today ===", dict(ctr)) + +# scheduled upload_at distribution +sched = [j for j in items if str(j.get("status")) in {"scheduled", "recorded"} and str(j.get("push_date")) == str(board.get("push_date") or "")] +due = [j for j in sched if float(j.get("upload_at") or 0) <= now] +future = [j for j in sched if float(j.get("upload_at") or 0) > now] +print("scheduled/recorded=", len(sched), "due_now=", len(due), "future=", len(future)) +if future: + waits = sorted(float(j.get("upload_at") or 0) - now for j in future)[:10] + print("next_waits_sec", [int(w) for w in waits]) + +# failed today +failed = [j for j in items if str(j.get("status")) == "failed"] +print("failed_sample=", len(failed)) +for j in failed[:8]: + print(" FAIL", j.get("channel_pk"), (j.get("error") or "")[:120]) + +# trigger fill +fill = call(op, base, "/api/shorts/fill-quota", method="POST", body={}) +print("\nfill just=", fill.get("just_quota_filled"), "gap_after=", fill.get("quota_gap")) + +# SSH deep: live rooms, claim blockers, yt quota +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command( + r"""python3 <<'PY' +import sqlite3, time, json +from pathlib import Path +p=Path('/opt/douyinWEB/backend/data/monitor.db') +conn=sqlite3.connect(str(p)); conn.row_factory=sqlite3.Row +# live rooms +live=conn.execute("SELECT COUNT(*) c FROM rooms WHERE enabled=1 AND last_status='live' AND room_id NOT LIKE 'yt:%'").fetchone()['c'] +print('live_douyin', live) +# today +import datetime +BJ=datetime.timezone(datetime.timedelta(hours=8)) +day=datetime.datetime.now(BJ).strftime('%Y-%m-%d') +print('day', day) +rows=conn.execute('''SELECT status, COUNT(*) c FROM shorts_jobs WHERE push_date=? GROUP BY status''',(day,)).fetchall() +print('jobs', {r['status']:r['c'] for r in rows}) +# due scheduled +now=time.time() +due=conn.execute('''SELECT COUNT(*) c FROM shorts_jobs WHERE push_date=? AND status IN ('scheduled','recorded') AND upload_at>0 AND upload_at<=?''',(day,now)).fetchone()['c'] +fut=conn.execute('''SELECT COUNT(*) c FROM shorts_jobs WHERE push_date=? AND status IN ('scheduled','recorded') AND upload_at>?''',(day,now)).fetchone()['c'] +print('due', due, 'future', fut) +# per channel used vs min for ypp-ish (join) +chs=conn.execute('SELECT id,name,daily_min,daily_max,oauth_profile_id,enabled FROM shorts_channels WHERE enabled=1').fetchall() +for ch in chs: + used=conn.execute('''SELECT COUNT(*) c FROM shorts_jobs WHERE channel_pk=? AND push_date=? AND status IN ('pending','recording','recorded','scheduled','uploading','uploaded','done')''',(ch['id'],day)).fetchone()['c'] + up=conn.execute('''SELECT COUNT(*) c FROM shorts_jobs WHERE channel_pk=? AND push_date=? AND status IN ('uploaded','done')''',(ch['id'],day)).fetchone()['c'] + sch=conn.execute('''SELECT COUNT(*) c FROM shorts_jobs WHERE channel_pk=? AND push_date=? AND status IN ('scheduled','recorded')''',(ch['id'],day)).fetchone()['c'] + if used < int(ch['daily_min'] or 9): + print(f"UNDER {ch['name']} prof={ch['oauth_profile_id']} used={used} up={up} sch={sch} min={ch['daily_min']}") +# settings gaps +for k in ('shorts_enabled','shorts_channel_min_gap_sec','shorts_upload_min_gap_sec','shorts_max_concurrent','shorts_upload_max_concurrent'): + r=conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone() + print('kv', k, r['value'] if r else None) +# recent errors +errs=conn.execute('''SELECT channel_pk,error,updated_at FROM shorts_jobs WHERE push_date=? AND error!='' ORDER BY updated_at DESC LIMIT 8''',(day,)).fetchall() +for r in errs: + print('err', r['channel_pk'], (r['error'] or '')[:100]) +conn.close() +PY""", + timeout=60, +) +print("\n=== ssh ===") +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("done") diff --git a/scripts/_diag_shorts_pace.py b/scripts/_diag_shorts_pace.py new file mode 100644 index 0000000..3f27087 --- /dev/null +++ b/scripts/_diag_shorts_pace.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +"""Diagnose why only 6/135 uploaded — upload_at spread + gaps.""" +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import sqlite3, time, datetime, json +from collections import Counter +BJ=datetime.timezone(datetime.timedelta(hours=8)) +now=time.time() +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +day=datetime.datetime.now(BJ).strftime('%Y-%m-%d') +print('day', day, 'now_bj', datetime.datetime.now(BJ).isoformat()) +# settings +for k in ('shorts_upload_min_gap_sec','shorts_channel_min_gap_sec','shorts_max_concurrent','shorts_upload_max_concurrent','shorts_upload_spread','shorts_auto_upload'): + r=con.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone() + print('kv', k, r[0] if r else None) +# job status counts +rows=con.execute('SELECT status, COUNT(*) c FROM shorts_jobs WHERE push_date=? GROUP BY status',(day,)).fetchall() +print('jobs', dict(rows)) +# scheduled with clip: upload_at histogram by hour BJ +sched=con.execute("""SELECT upload_at, status, channel_pk, clip_path FROM shorts_jobs + WHERE push_date=? AND status IN ('scheduled','recorded')""",(day,)).fetchall() +hours=Counter(); due=0; future=0; no_clip=0 +for r in sched: + clip=str(r['clip_path'] or '').strip() + if not clip: + no_clip+=1 + continue + ua=float(r['upload_at'] or 0) + if ua<=0: + hours['no_at']+=1 + continue + if ua<=now+60: due+=1 + else: future+=1 + h=datetime.datetime.fromtimestamp(ua,BJ).hour + hours[h]+=1 +print('clip_ready scheduled/recorded', len(sched)-no_clip, 'no_clip', no_clip, 'due_now', due, 'future', future) +print('upload_at by hour BJ', dict(sorted(hours.items()))) +# uploaded count +up=con.execute("SELECT COUNT(*) FROM shorts_jobs WHERE push_date=? AND status IN ('uploaded','done')",(day,)).fetchone()[0] +print('uploaded', up) +# channels +chs=con.execute('SELECT COUNT(*) FROM shorts_channels WHERE enabled=1').fetchone()[0] +print('enabled_channels', chs) +# next 10 due +print('=== next upload slots ===') +for r in con.execute("""SELECT id, upload_at, status, channel_pk FROM shorts_jobs + WHERE push_date=? AND status IN ('scheduled','recorded') AND IFNULL(clip_path,'')!='' + ORDER BY CASE WHEN upload_at<=0 THEN 1e18 ELSE upload_at END ASC LIMIT 12""",(day,)): + ua=float(r['upload_at'] or 0) + bj=datetime.datetime.fromtimestamp(ua,BJ).strftime('%H:%M:%S') if ua>0 else '-' + print(bj, 'in', int(ua-now) if ua else '?', 's', r['status'], str(r['channel_pk'])[:8]) +con.close() +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command("python3 - <<'PY'\n" + REMOTE + "\nPY", timeout=60) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err: + print("STDERR", err[:1000]) +c.close() diff --git a/scripts/_diag_tm_script_payload.py b/scripts/_diag_tm_script_payload.py new file mode 100644 index 0000000..b090180 --- /dev/null +++ b/scripts/_diag_tm_script_payload.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Check TM script payload size + provisioning on dylive neko-2; compare dy if reachable.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", host, i, e) + time.sleep(2) + raise SystemExit(f"fail {host}") + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +cmd = r""" +set +e +echo '=== provisioning files ===' +ls -la /opt/douyinWEB/backend/neko/provisioning/ +echo +echo '=== TM leveldb strings (scripts?) on running nekos ===' +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + echo "--- $name ---" + docker exec "$name" sh -c ' +sz=$(du -sb "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" 2>/dev/null | awk "{print \$1}") +echo "tm_settings_bytes=$sz" +# extract printable hints +python3 - <<"PY" +import os,re +p="/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +files=[] +for root,_,fs in os.walk(p): + for f in fs: + files.append(os.path.join(root,f)) +blob=b"" +for f in files: + try: + blob += open(f,"rb").read() + except Exception: + pass +text=blob.decode("latin1","ignore") +# look for userscript markers +hits=re.findall(r"@name[^\x00]{0,80}|youtube-studio[^\x00]{0,40}|UserScript[^\x00]{0,40}|live-ops[^\x00]{0,40}", text) +print("markers", len(hits)) +for h in hits[:15]: + print(" ", repr(h)[:100]) +print("blob_len", len(blob)) +PY +curl -sS -m 2 http://127.0.0.1:8080/ 2>/dev/null | head -c 80; echo +' +done + +echo +echo '=== how provisioning works ===' +ls /opt/douyinWEB/backend/neko/provisioning/ +head -80 /opt/douyinWEB/backend/neko/provisioning/*.json 2>/dev/null +grep -RIn "tampermonkey\|userscript\|provision" /opt/douyinWEB/backend/neko --include="*.sh" --include="*.py" --include="*.conf" 2>/dev/null | head -40 + +echo +echo '=== live-ops extension ===' +ls /opt/douyinWEB/backend/neko/live-ops-extension/ | head +docker exec douyinweb-neko-2 sh -c "ls /etc/neko/live-ops-extension | head; grep -n load-extension /etc/neko/browser-launch.sh | head" +""" + +print("===== dylive =====", flush=True) +dl = ssh("107.173.30.245") +print(run(dl, cmd), flush=True) +dl.close() + +print("===== dy (compare healthy) =====", flush=True) +dy = ssh("108.174.50.68") +print( + run( + dy, + r""" +set +e +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + echo "--- $name ---" + docker exec "$name" sh -c ' +sz=$(du -sb "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" 2>/dev/null | awk "{print \$1}") +echo "tm_settings_bytes=$sz running" +python3 - <<"PY" +import os,re +p="/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +blob=b"" +for root,_,fs in os.walk(p): + for f in fs: + try: blob+=open(os.path.join(root,f),"rb").read() + except: pass +hits=re.findall(r"@name[^\x00]{0,60}|youtube-studio[^\x00]{0,40}", blob.decode("latin1","ignore")) +print("markers",len(hits),"blob",len(blob)) +for h in hits[:8]: print(" ",repr(h)[:90]) +PY +' +done +""", + ), + flush=True, +) +dy.close() +print("DONE") diff --git a/scripts/_diag_vps_neko_should_stop.py b/scripts/_diag_vps_neko_should_stop.py new file mode 100644 index 0000000..5bbf0cb --- /dev/null +++ b/scripts/_diag_vps_neko_should_stop.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Why VPS local Nekos show Chrome when they should be stopped by default.""" +import json +import sys + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + remote = r""" +echo '=== docker assign nekos ===' +docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep -E 'NAMES|douyinweb-neko-' | head -40 +echo '=== who owns 920x ===' +ss -lntp | grep -E ':920[0-9]' | head -20 +echo '=== ssh tunnels? ===' +ps aux | grep -E '920[0-9]|neko|frp' | grep -v grep | head -30 +echo '=== host profile / settings ===' +cd /opt/douyinWEB/backend +PY=python3; [ -x .venv/bin/python ] && PY=.venv/bin/python +$PY - <<'PY' +import sqlite3, json +from pathlib import Path +db=Path('data/monitor.db') +con=sqlite3.connect(f'file:{db}?mode=ro', uri=True) +con.row_factory=sqlite3.Row +cur=con.cursor() +# kv settings related +for k in ('host_profile','youtube_relay_exclusive_live','youtube_relay_enabled'): + try: + r=cur.execute("select value from kv_settings where key=?", (k,)).fetchone() + print('kv', k, r['value'] if r else None) + except Exception as e: + # maybe different schema + pass +try: + rows=cur.execute("select key, value from kv_settings where key like '%host%' or key like '%neko%' or key like '%exclusive%' or key like '%relay_enabled%'").fetchall() + for r in rows: + print('set', r['key'], str(r['value'])[:80]) +except Exception as e: + print('kv_err', e) + # try settings table + try: + rows=cur.execute("select key, value from settings where key like '%host%' or key like '%neko%' or key like '%exclusive%' or key like '%relay%'").fetchall() + for r in rows: print('set2', r[0], str(r[1])[:80]) + except Exception as e2: + print('set2_err', e2) +rows=cur.execute("select name, neko_instance_id, neko_enabled, category from yt_assign_groups order by neko_instance_id").fetchall() +print('=== groups neko_enabled ===') +for r in rows: + print(dict(r)) +con.close() +PY +""" + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_vps_neko_default.sh", "wb") as f: + f.write(remote.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_vps_neko_default.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + + # API status + client = httpx.Client(base_url="https://dylive.nomadro.com", timeout=40, follow_redirects=True) + r = client.post("/api/auth/login", json={"username": "hackrobot", "password": "Xiao4669805@"}) + print("login", r.status_code) + st = client.get("/api/youtube/neko/status").json() + print("neko status available", st.get("available"), "count", len(st.get("instances") or [])) + for inst in (st.get("instances") or [])[:12]: + print( + json.dumps( + { + "id": inst.get("id"), + "running": inst.get("running"), + "ready": inst.get("ready"), + "status": inst.get("status"), + "studio_url": (inst.get("studio_url") or "")[:60], + }, + ensure_ascii=False, + ) + ) + hp = client.get("/api/ops/host-profile").json() + print("host_profile", json.dumps(hp, ensure_ascii=False)[:500]) + client.close() + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_vps_neko_tm.py b/scripts/_diag_vps_neko_tm.py new file mode 100644 index 0000000..d2d95a9 --- /dev/null +++ b/scripts/_diag_vps_neko_tm.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose Tampermonkey on VPS assign Nekos (esp #8).""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r""" +set -e +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +echo '=== policies ===' +python3 - <<'PY' +import json +from pathlib import Path +for p in [ + Path('/opt/douyinWEB/backend/neko/policies/policies.json'), + Path('/etc/neko/policies/policies.json'), +]: + if p.exists(): + d=json.loads(p.read_text()) + print(p, 'forcelist', d.get('ExtensionInstallForcelist')) + print(' jsonImport', ((d.get('3rdparty') or {}).get('extensions') or {}).get('dhdgffkkebhmkfjojejmpbldmpobfkfo')) +PY +echo '=== browser-launch tm flags ===' +grep -nE 'Offline Tampermonkey|tm_load_dir|load-extension|ExtensionInstall' /opt/douyinWEB/backend/neko/browser-launch.sh | head -30 +echo '=== containers ===' +docker ps -a --format '{{.Names}} {{.Status}}' | grep 'douyinweb-neko-' | sort +for i in 1 2 3 4 5 6 7 8; do + name=douyinweb-neko-$i + if ! docker ps --format '{{.Names}}' | grep -qx "$name"; then + echo "===== $name NOT_RUNNING =====" + continue + fi + echo "===== $name =====" + docker exec "$name" bash -lc ' + EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo + P=/home/neko/.config/google-chrome/Default + echo -n "ext_dir "; ls -d "$P/Extensions/$EXT"/*/ 2>/dev/null | head -1 || echo MISSING + echo -n "les "; ls "$P/Local Extension Settings/$EXT" 2>/dev/null | wc -l + python3 - </dev/null | wc -l") +print("script_hits", hits.strip()) +# policy inside +try: + pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) + print("in_forcelist", pol.get("ExtensionInstallForcelist")) +except Exception as e: + print("pol_err", e) +PY + ' || echo EXEC_FAIL +done +# google update reachable? +echo '=== clients2.google.com from neko-8 ===' +docker exec douyinweb-neko-8 bash -lc 'curl -sS -m 5 -o /dev/null -w "%{http_code}\n" https://clients2.google.com/service/update2/crx || echo FAIL' +echo '=== provisioning hash ===' +ls -la /opt/douyinWEB/backend/neko/provisioning/ | head +grep -E 'hash|Auto Dismiss|version' /opt/douyinWEB/backend/neko/provisioning/tampermonkey-provisioning.json 2>/dev/null | head -10 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_vps_tm.sh", "wb") as f: + f.write(REMOTE.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_vps_tm.sh", timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_vps_neko_url.py b/scripts/_diag_vps_neko_url.py new file mode 100644 index 0000000..a528c3d --- /dev/null +++ b/scripts/_diag_vps_neko_url.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r""" +set -e +echo '=== env ===' +grep -E 'DY_PUBLIC|PUBLIC_BASE|NEKO' /opt/douyinWEB/backend/.env 2>/dev/null | head -30 || true +systemctl show douyinweb-api -p Environment 2>/dev/null | tr ' ' '\n' | grep -E 'DY_PUBLIC|PUBLIC_BASE|NEKO' | head -30 || true +ls /etc/systemd/system/douyinweb-api.service.d 2>/dev/null || true +echo '=== python ===' +cd /opt/douyinWEB/backend +PY=python3 +[ -x .venv/bin/python ] && PY=.venv/bin/python +$PY - <<'PY' +import os, sys +sys.path.insert(0, ".") +from app.config import settings +from app import youtube_neko +print("settings.public_base_url", repr(settings.public_base_url)) +print("env DY_PUBLIC", repr(os.environ.get("DY_PUBLIC_BASE_URL"))) +print("_public_base", repr(youtube_neko._public_base())) +print("physical_dual", youtube_neko._physical_dual_edge()) +print("preferred", repr(youtube_neko.preferred_neko_public_base())) +print("studio6", youtube_neko.public_studio_url(6)) +print("studio8", youtube_neko.public_studio_url(8)) +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_diag_neko_url.sh", "wb") as f: + f.write(REMOTE.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_diag_neko_url.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_wg_129_10_88.py b/scripts/_diag_wg_129_10_88.py new file mode 100644 index 0000000..950dd35 --- /dev/null +++ b/scripts/_diag_wg_129_10_88.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Read-only: WG hub 129.204.21.129 → 10.88.0.8:8001 (PVE guest).""" +from __future__ import annotations + +import socket +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(host, port, user, passwords, label): + last = None + for pw in passwords: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(4): + try: + c.connect( + host, + port, + user, + pw, + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + print(f"{label}: ok user={user} pw_len={len(pw)}", flush=True) + return c + except Exception as e: + last = e + print(f"{label}: retry {user} {i}: {type(e).__name__}: {e}", flush=True) + time.sleep(2) + print(f"{label}: FAIL {last}", flush=True) + return None + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +# 1) local from Windows +print("=== local TCP ===", flush=True) +for host, port in [("129.204.21.129", 80), ("129.204.21.129", 22), ("10.88.0.8", 8001)]: + s = socket.socket() + s.settimeout(5) + try: + s.connect((host, port)) + print(f"local {host}:{port} OK") + except Exception as e: + print(f"local {host}:{port} FAIL {e}") + finally: + s.close() + +# 2) WG hub VPS +print("\n======== WG hub 129.204.21.129 ========", flush=True) +hub = connect("129.204.21.129", 22, "ubuntu", ["Xiao4669805"], "hub") +if hub: + print( + run( + hub, + r""" +set +e +whoami; hostname; uname -a | head -1 +echo '--- listen 80 / wg ---' +ss -lntp | grep -E ':80\b|:8001\b|:518|wg' | head -30 +echo '--- wg ---' +sudo wg show 2>/dev/null || wg show 2>/dev/null +echo +ip -br a | grep -E 'wg|10\.88' || true +echo '--- route to 10.88.0.8 ---' +ip route get 10.88.0.8 2>&1 +echo '--- peer reachability ---' +ping -c 3 -W 2 10.88.0.8 2>&1 | tail -6 +curl -sS -m 8 -o /tmp/out8001.txt -w 'curl=%{http_code} bytes=%{size_download} time=%{time_total}\n' http://10.88.0.8:8001/ || echo curl_fail +head -c 300 /tmp/out8001.txt 2>/dev/null; echo +echo '--- conf snippets ---' +sudo ls -la /etc/wireguard/ 2>/dev/null +sudo grep -RIn '10\.88\|AllowedIPs\|Address\|ListenPort\|Endpoint' /etc/wireguard/ 2>/dev/null | head -60 +echo '--- docker/services mentioning 8001 ---' +sudo ss -lntp | grep 8001 || true +""", + ), + flush=True, + ) + hub.close() + +# 3) try reach PVE guest via known paths +print("\n======== try PVE/physical paths ========", flush=True) +# overseas VPS FRP SSH to physical eric +paths = [ + ("frp4014", "107.173.30.245", 4014, "eric", ["4669805", "Xiao4669805"]), + ("dy_direct", "108.174.50.68", 22, "root", ["Xiao4669805"]), + ("vps_root", "107.173.30.245", 22, "root", ["Xiao4669805"]), +] +for label, host, port, user, pws in paths: + c = connect(host, port, user, pws, label) + if not c: + continue + print( + f"--- on {label}: look for 10.88 / :8001 ---", + flush=True, + ) + print( + run( + c, + r""" +set +e +hostname; ip -br a | head -20 +echo '--- wg / 10.88 ---' +wg show 2>/dev/null | head -40 +ip -br a | grep -E '10\.88|wg' || true +ip route get 10.88.0.8 2>&1 || true +ping -c 2 -W 2 10.88.0.8 2>&1 | tail -4 +curl -sS -m 5 -o /dev/null -w 'curl_10.88=%{http_code}\n' http://10.88.0.8:8001/ || echo curl_fail +echo '--- local :8001 ---' +ss -lntp | grep ':8001' || true +docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null | grep 8001 || true +# if this host IS 10.88.0.8 +ip -br a | grep '10.88.0.8' && echo 'THIS_HOST_IS_10.88.0.8' +""", + t=60, + ), + flush=True, + ) + c.close() + +print("DONE") diff --git a/scripts/_diag_wg_bind_live.py b/scripts/_diag_wg_bind_live.py new file mode 100644 index 0000000..c30fb0f --- /dev/null +++ b/scripts/_diag_wg_bind_live.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def sh(port, user, pw, cmd, t=50): + print(f"## {user}@{port}", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print("connected", flush=True) + print("$", cmd[:200], flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + c.close() + + +sh( + 4014, + "eric", + "4669805", + "echo 4669805 | sudo -S -p '' bash -lc '" + "ss -lntp | grep -E \":(8014|4015)\"; " + "ip addr show wg-dy; " + "ip route | head -20; " + "curl -sS -m 5 -o /dev/null -w local=%{http_code}\\\\n http://127.0.0.1:8014/api/health; " + "curl -sS -m 5 -o /dev/null -w via_self=%{http_code}\\\\n http://10.8.0.2:8014/api/health; " + "wg show; " + "sudo iptables -L INPUT -n | head -25" + "'", +) + +sh( + 22, + "root", + "Xiao4669805", + "wg show wg-dy; " + "ping -c 2 -W 2 10.8.0.2 | tail -4; " + "curl -sS -m 8 -o /dev/null -w via_wg=%{http_code}\\\\n http://10.8.0.2:8014/api/health; " + "curl -sS -m 8 -o /dev/null -w via_wg_web=%{http_code}\\\\n http://10.8.0.2:4015/; " + "iptables -L INPUT -n | grep 51820 || true", +) + +with httpx.Client(follow_redirects=False, timeout=12) as cl: + for u in ["https://dy.nomadro.com/api/health", "https://dylive.nomadro.com/api/health"]: + try: + print(u, cl.get(u).status_code, flush=True) + except Exception as ex: + print(u, ex, flush=True) +print("DONE", flush=True) diff --git a/scripts/_diag_why_neko_broke.py b/scripts/_diag_why_neko_broke.py new file mode 100644 index 0000000..81a0b21 --- /dev/null +++ b/scripts/_diag_why_neko_broke.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""READ-ONLY: explain what touched Neko vs frpp SSH. Log timeline only.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + return c + except Exception as ex: + print("retry", port, i, ex, flush=True) + time.sleep(3) + raise SystemExit(f"ssh {port} fail") + + +def run(c, cmd, t=90): + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.recv_exit_status() + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +print("===== VPS: frpp vs dy-frp-http-aux (what I touched) =====", flush=True) +v = ssh(22, "root", "Xiao4669805") +run( + v, + r""" +set +e +echo '--- units ---' +systemctl is-active frpp dy-frp-http-aux caddy +systemctl is-enabled frpp dy-frp-http-aux 2>/dev/null +echo '--- frpp = YOUR SSH panel (should be untouched) ---' +systemctl cat frpp 2>/dev/null | head -40 +echo '--- dy-frp-http-aux = EXTRA ssh -L tunnels (THIS is what was remapped) ---' +systemctl cat dy-frp-http-aux 2>/dev/null | head -50 +echo '--- bak files (proof of edits) ---' +ls -lt /etc/systemd/system/dy-frp-http-aux.service* 2>/dev/null | head -10 +ls -lt /etc/caddy/sites/dy.nomadro.com.caddy* 2>/dev/null | head -15 +echo '--- journal dy-frp-http-aux today ---' +journalctl -u dy-frp-http-aux --since '2026-09-05 16:00:00' --no-pager 2>/dev/null | tail -60 +echo '--- journal frpp today (should be calm) ---' +journalctl -u frpp --since '2026-09-05 16:00:00' --no-pager 2>/dev/null | tail -20 +echo '--- caddy reload today ---' +journalctl -u caddy --since '2026-09-05 16:00:00' --no-pager 2>/dev/null | grep -iE 'reload|stop|start|error' | tail -30 +""", +) +v.close() + +print("===== PHYSICAL: Neko/chrome timeline =====", flush=True) +p = ssh(4014, "eric", "4669805") +run( + p, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +echo "--- container StartedAt (not recreate if old) ---" +docker ps -a --filter name=douyinweb-neko --filter name=douyinweb-ops-neko \ + --format "{{.Names}}\t{{.Status}}\t{{.CreatedAt}}" +echo "--- docker events: create/destroy/die last 8h (exclude healthcheck noise) ---" +docker events --since 8h --until 0s --filter type=container 2>/dev/null \ + | grep -iE "douyinweb-(neko|ops-neko)" \ + | grep -iE " create | destroy | die | start | stop | kill | restart " \ + | grep -vi health \ + | tail -80 +echo "--- api journal mentions compose/recreate/neko start last 8h ---" +journalctl -u douyinweb-api --since "8 hours ago" --no-pager 2>/dev/null \ + | grep -iE "force-recreate|compose up|recreate_all|docker rm|supervisorctl|neko" \ + | grep -viE "remote-catalog|GET /api" \ + | tail -40 +echo "--- auth.log sudo from eric (who ran what) last 8h ---" +journalctl -u ssh --since "8 hours ago" --no-pager 2>/dev/null | tail -5 +grep -E "sudo|COMMAND" /var/log/auth.log 2>/dev/null | tail -40 +' +""", +) +p.close() +print("DONE", flush=True) diff --git a/scripts/_diag_why_no_autorelay.py b/scripts/_diag_why_no_autorelay.py new file mode 100644 index 0000000..9974c49 --- /dev/null +++ b/scripts/_diag_why_no_autorelay.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Why isn't auto-relay starting for nomadvlog despite ops-neko ready.""" +import json +import sys +import paramiko +import httpx + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CREDS = [("hackrobot", "Xiao4669805@"), ("hackrobot", "Xiao4669805@!"), ("admin", "Xiao4669805@")] + + +def login(base: str) -> httpx.Client: + for u, p in CREDS: + c = httpx.Client(base_url=base, timeout=40, follow_redirects=True) + r = c.post("/api/auth/login", json={"username": u, "password": p}) + if r.status_code < 400: + print(f"login {base} as {u} ok") + return c + c.close() + raise SystemExit(f"login fail {base}") + + +def main() -> None: + for base in ("https://dy.nomadro.com", "https://dy.nomadro.cn", "https://dylive.nomadro.com"): + try: + h = httpx.get(f"{base}/api/health", timeout=15) + print(base, "health", h.status_code, h.text[:80]) + except Exception as e: + print(base, "health ERR", e) + + # prefer physical (assign lives there for dual deploy) + bases = ["https://dy.nomadro.com", "https://dy.nomadro.cn"] + c = None + used = None + for b in bases: + try: + c = login(b) + used = b + break + except Exception as e: + print("login skip", b, e) + if not c: + raise SystemExit("no login") + + print("\n=== using", used, "===") + for path in ( + "/api/youtube/relay/status", + "/api/youtube/assign/groups", + "/api/youtube/relay/settings", + "/api/ops/neko/remote-catalog", + ): + try: + r = c.get(path) + print(f"\n--- GET {path} {r.status_code} ---") + data = r.json() if r.headers.get("content-type", "").startswith("application/json") else {"raw": r.text[:500]} + if path.endswith("groups"): + groups = data.get("groups") or data if isinstance(data, list) else data.get("groups") or [] + if isinstance(data, dict) and "groups" not in data and isinstance(data.get("items"), list): + groups = data["items"] + if not isinstance(groups, list): + # maybe top-level list + groups = data if isinstance(data, list) else [] + print("groups", len(groups) if isinstance(groups, list) else type(groups)) + for g in (groups if isinstance(groups, list) else [])[:20]: + if not isinstance(g, dict): + continue + name = g.get("youtube_title") or g.get("name") or g.get("id") + print( + json.dumps( + { + "id": g.get("id"), + "title": name, + "category": g.get("category"), + "enabled": g.get("enabled"), + "neko_open_prefer": g.get("neko_open_prefer"), + "ops_slot": g.get("ops_neko_slot"), + "ops_url": (g.get("ops_neko_open_url") or "")[:60], + "neko_id": g.get("neko_instance_id"), + "neko_en": g.get("neko_enabled"), + "stream_key_set": bool(str(g.get("stream_key") or "").strip()), + }, + ensure_ascii=False, + ) + ) + elif path.endswith("settings"): + print(json.dumps(data, ensure_ascii=False, indent=2)[:2000]) + elif path.endswith("status"): + # summarize + if isinstance(data, dict): + print("keys", sorted(data.keys())[:40]) + for k in ("auto_enabled", "auto_relay", "master", "exclusive", "settings", "global"): + if k in data: + print(k, data[k]) + sessions = data.get("sessions") or data.get("groups") or data.get("items") or [] + if isinstance(sessions, list): + print("session_count", len(sessions)) + for s in sessions[:15]: + if isinstance(s, dict): + print( + json.dumps( + { + "id": s.get("group_id") or s.get("id"), + "title": s.get("title") or s.get("youtube_title"), + "state": s.get("state") or s.get("status"), + "running": s.get("running"), + "reason": s.get("reason") or s.get("wait_reason") or s.get("message"), + "dy_live": s.get("dy_live") or s.get("source_live"), + "ffmpeg": s.get("ffmpeg_pid") or s.get("pid"), + }, + ensure_ascii=False, + ) + ) + print(json.dumps({k: data[k] for k in data if k in ( + "auto_push", "auto_enabled", "relay_auto", "worker", "exclusive_live", + "time_slot", "settings", "flags", "pipeline" + )}, ensure_ascii=False, indent=2)[:1500]) + else: + print(json.dumps(data, ensure_ascii=False)[:1500]) + except Exception as e: + print(path, "ERR", e) + + # also dump kv / relay flags from physical via ssh if needed + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_diag_yt_thumbs_neko_status.py b/scripts/_diag_yt_thumbs_neko_status.py new file mode 100644 index 0000000..8b51da3 --- /dev/null +++ b/scripts/_diag_yt_thumbs_neko_status.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Probe YouTube manage profile thumbs + studio status for nice street food.""" +from __future__ import annotations + +import json +import ssl +import sys +import urllib.request +from http.cookiejar import CookieJar + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def probe(site: str): + print(f"\n=== {site} ===", flush=True) + cj = CookieJar() + opener = urllib.request.build_opener( + urllib.request.HTTPSHandler(context=CTX), + urllib.request.HTTPCookieProcessor(cj), + ) + body = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + site + "/api/auth/login", + data=body, + headers={"Content-Type": "application/json"}, + method="POST", + ) + with opener.open(req, timeout=30) as r: + print("login", r.status) + with opener.open(site + "/api/youtube/manage/profiles", timeout=40) as r: + data = json.loads(r.read().decode()) + profiles = data.get("profiles") or {} + print("profiles", len(profiles)) + for pk, p in list(profiles.items())[:12]: + thumb = (p.get("thumb_url") or "") if isinstance(p, dict) else "" + title = (p.get("title") or "") if isinstance(p, dict) else "" + status = "-" + if thumb.startswith("http"): + try: + with opener.open(thumb, timeout=12) as ir: + status = f"{ir.status}:{ir.headers.get('content-type','')[:20]}" + except Exception as e: + status = f"FAIL:{e}" + print({"pk": pk[:8], "title": title[:40], "thumb": thumb[:90], "fetch": status}) + + with opener.open(site + "/api/youtube/assign/groups", timeout=30) as r: + groups = json.loads(r.read().decode()).get("groups") or [] + for g in groups: + if "nice" in str(g.get("name") or "").lower() or "street" in str(g.get("name") or "").lower(): + print("group", {k: g.get(k) for k in ( + "id","name","neko_instance_id","neko_enabled","ops_neko_prefer","ops_neko_slot","channel_pk" + )}) + gid = g.get("id") + break + else: + gid = groups[0]["id"] if groups else "" + print("first_group", groups[0].get("name") if groups else None) + + # studio status if any + try: + with opener.open(site + "/api/youtube/studio/status", timeout=20) as r: + st = json.loads(r.read().decode()) + print("studio_keys", list(st.keys())[:20] if isinstance(st, dict) else type(st)) + items = st.get("items") or st.get("groups") or st.get("status") or st + if isinstance(items, dict): + for k, v in list(items.items())[:5]: + if isinstance(v, dict): + print("studio", k[:8], {kk: v.get(kk) for kk in ("on_air","live_page_open","viewer_count","neko_kind","ui_source")}) + elif isinstance(items, list): + for v in items[:5]: + print("studio", {kk: v.get(kk) for kk in ("group_id","on_air","live_page_open","viewer_count")}) + except Exception as e: + print("studio_err", e) + + # neko status for instance 10 + try: + with opener.open(site + "/api/youtube/neko/10/status", timeout=20) as r: + print("neko10", json.loads(r.read().decode())) + except Exception as e: + print("neko10_err", e) + + +for s in ("https://dylive.nomadro.com", "https://dy.nomadro.live"): + try: + probe(s) + except Exception as e: + print("SITE_ERR", s, e) +print("ALL_DONE", flush=True) diff --git a/scripts/_dump_studio_telemetry.py b/scripts/_dump_studio_telemetry.py new file mode 100644 index 0000000..6f550e0 --- /dev/null +++ b/scripts/_dump_studio_telemetry.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +"""Dump studio telemetry + yt_studio DB for assign groups.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, sqlite3, glob, os, time +os.chdir("/opt/douyinWEB/backend") +con=sqlite3.connect("data/monitor.db") +con.row_factory=sqlite3.Row +print("=== assign groups ===") +for r in con.execute("select id,name,youtube_channel_id,channel_pk,ops_neko_slot,neko_open_prefer from yt_assign_groups where enabled=1"): + d=dict(r) + print(d["name"], d["id"][:8], "cid", (d.get("youtube_channel_id") or "")[:14], "slot", d.get("ops_neko_slot"), "prefer", d.get("neko_open_prefer")) + +print("=== tables with studio ===") +tabs=[r[0] for r in con.execute("select name from sqlite_master where type='table'")] +print([t for t in tabs if "studio" in t.lower() or "neko" in t.lower() or "tele" in t.lower()]) + +for t in tabs: + if "studio" in t.lower(): + cols=[r[1] for r in con.execute(f"pragma table_info({t})")] + print("table", t, cols) + try: + rows=list(con.execute(f"select * from {t} order by rowid desc limit 15")) + for r in rows: + print(" ", dict(r)) + except Exception as e: + print(" err", e) + +print("=== telemetry files ===") +for p in sorted(glob.glob("data/neko/**/*.json", recursive=True))[:40]: + try: + obj=json.load(open(p,encoding="utf-8")) + except Exception: + continue + # summarize + if isinstance(obj, dict): + pl=obj.get("payload") or obj + ls=pl.get("live_status") or obj.get("live_status") + url=pl.get("url") or obj.get("url") or "" + ref=obj.get("neko_ref") or pl.get("neko_ref") or "" + on=pl.get("on_air") or pl.get("encoder_receiving") + age=None + ra=obj.get("received_at") or pl.get("received_at") + if isinstance(ra,(int,float)): + # handle weird future timestamps + age=ra + if ls or "studio" in p: + print(p, "ref", ref, "status", ls, "on_air/enc", on, "url", (url or "")[:70], "recv", ra) + +print("=== minute jsonl tails ===") +for p in sorted(glob.glob("data/neko/studio_minute/*.jsonl")): + try: + lines=open(p,encoding="utf-8").read().strip().splitlines()[-3:] + print(p, "n", len(open(p,encoding="utf-8").read().strip().splitlines())) + for ln in lines: + o=json.loads(ln) + pl=o.get("payload") or o + print(" ", pl.get("live_status"), pl.get("on_air"), (pl.get("url") or "")[:60], pl.get("stream_title","")[:40]) + except Exception as e: + print(p, e) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=60) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-800:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys") diff --git a/scripts/_dy_frp_http_aux.py b/scripts/_dy_frp_http_aux.py new file mode 100644 index 0000000..ba4bb93 --- /dev/null +++ b/scripts/_dy_frp_http_aux.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Emergency: dy.nomadro.com via SSH-FRP local forwards (WG one-way dead). +Physical FRP: 127.0.0.1:4014 eric/4669805 on VPS. +Maps: + VPS 127.0.0.1:18014 -> guest 127.0.0.1:8014 + VPS 127.0.0.1:14015 -> guest 127.0.0.1:4015 +Caddy dy.nomadro.com temporarily points at these instead of 10.8.0.2. +No Neko. Live flush. +""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" +ROOT_PW = "Xiao4669805" +GUEST_PW = "4669805" + + +def connect(): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + ROOT_PW, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print("connected", flush=True) + return c + except Exception as ex: + print(f"retry {i} {ex}", flush=True) + time.sleep(2) + raise RuntimeError("ssh fail") + + +def run(c, cmd, t=120): + print(f"$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +REMOTE = r''' +set -e +SITE=/etc/caddy/sites/dy.nomadro.com.caddy +cp -a "$SITE" "$SITE.bak.frpaux.$(date +%s)" + +# Install sshpass if needed for non-interactive ssh +command -v sshpass >/dev/null || apt-get install -y sshpass >/dev/null 2>&1 || true + +# systemd unit for FRP-aux HTTP tunnels (via existing :4014) +cat >/etc/systemd/system/dy-frp-http-aux.service <<'EOF' +[Unit] +Description=dy.nomadro.com FRP-aux HTTP tunnels (8014/4015 via :4014) +After=network-online.target frpp.service +Wants=network-online.target + +[Service] +Type=simple +Restart=always +RestartSec=3 +Environment=SSHPASS=4669805 +ExecStart=/usr/bin/sshpass -e ssh -N -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -L 127.0.0.1:18014:127.0.0.1:8014 -L 127.0.0.1:14015:127.0.0.1:4015 -p 4014 eric@127.0.0.1 + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl enable --now dy-frp-http-aux.service +sleep 2 +systemctl is-active dy-frp-http-aux.service +ss -lntp | grep -E ':(18014|14015)\b' || true +curl -sS -m 8 http://127.0.0.1:18014/api/health | head -c 160; echo +curl -sS -m 8 -o /dev/null -w 'aux_web=%{http_code}\n' http://127.0.0.1:14015/ + +# Point Caddy main app proxies to FRP-aux locals (keep neko ports on 10.8.0.2 for now) +# Only replace API/web backends that use 8014/4015 +python3 - <<'PY' +from pathlib import Path +p = Path("/etc/caddy/sites/dy.nomadro.com.caddy") +text = p.read_text(encoding="utf-8") +# common patterns +text2 = text.replace("reverse_proxy 10.8.0.2:8014", "reverse_proxy 127.0.0.1:18014") +text2 = text2.replace("reverse_proxy 10.8.0.2:4015", "reverse_proxy 127.0.0.1:14015") +if text2 == text: + print("WARN: no 8014/4015 replacements made") +else: + p.write_text(text2, encoding="utf-8") + print("caddy site rewritten 8014/4015 -> frp-aux") +print("sample:") +for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1): + if "reverse_proxy" in line and ("18014" in line or "14015" in line or "8014" in line or "4015" in line): + print(f"{i}:{line}") +PY + +caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20 +systemctl reload caddy || systemctl restart caddy +sleep 2 +systemctl is-active caddy +''' + +print("## install FRP-aux tunnels + retarget Caddy", flush=True) +c = connect() +run(c, REMOTE, t=180) +c.close() + +print("## public", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for u in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.com/login", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code} loc={(r.headers.get('location') or '')[:40]}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_dylive_neko_exclusive_one.py b/scripts/_dylive_neko_exclusive_one.py new file mode 100644 index 0000000..039a771 --- /dev/null +++ b/scripts/_dylive_neko_exclusive_one.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""dylive: turn off neko_enabled on all but one; stop extras. Prevent OOM restart loop.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +KEEP = 2 # hackrobotlite + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +_i, o, e = c.exec_command( + f""" +set +e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +KEEP = {KEEP} +changed = [] +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + nid = int(g.get('neko_instance_id') or 0) + en = bool(g.get('neko_enabled')) + if nid == KEEP: + if not en: + yt_assign_db.update_group(g['id'], neko_enabled=True) + changed.append(('on', g.get('name'), nid)) + continue + if en: + yt_assign_db.update_group(g['id'], neko_enabled=False) + changed.append(('off', g.get('name'), nid)) +print('changed', changed) +# sync without reconcile_running (don't stop/start blindly beyond flags) +from app import youtube_neko +print(youtube_neko.sync_for_groups(yt_assign_db.list_groups(include_urls=False), reconcile_running=False)) +PY + +# stop every running neko except KEEP +for n in $(docker ps --format '{{{{.Names}}}}' | grep '^douyinweb-neko-'); do + case "$n" in + douyinweb-neko-{KEEP}) echo keep $n ;; + *) echo stop $n; docker stop "$n" ;; + esac +done +# ensure KEEP up +docker start douyinweb-neko-{KEEP} 2>/dev/null || true +sleep 8 +docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort -V +free -m | head -2 +uptime +curl -sS -m 8 -o /dev/null -w 'fe:%{{{{http_code}}}}\\n' http://127.0.0.1:4015/youtube +curl -sS -m 8 -o /dev/null -w 'api:%{{{{http_code}}}}\\n' http://127.0.0.1:8014/api/health +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_emergency_dylive_ram_revive.py b/scripts/_emergency_dylive_ram_revive.py new file mode 100644 index 0000000..2754c2a --- /dev/null +++ b/scripts/_emergency_dylive_ram_revive.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Emergency: free RAM on dylive, revive API/web. Never recreate Neko; docker stop OK.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=90, + ) + break + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2) +else: + raise SystemExit("ssh fail") + + +def run(cmd: str, t: int = 90) -> str: + print(f"\n$ {cmd[:100]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + out = (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + out = f"TIMEOUT/ERR {ex}\n" + print(out[-6000:] if len(out) > 6000 else out, flush=True) + return out + + +run("free -m | head -2; uptime") +run("ps aux --sort=-%mem | head -15") +# stop ALL douyinweb-neko to free RAM (start later if needed) — no recreate +run( + "docker ps -q --filter name=douyinweb-neko | xargs -r docker stop; " + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort", + t=120, +) +# stop leftover non-app if any (ntfy etc) — user previously OK stopping WP/umami/nsq +run( + "docker ps --format '{{.Names}}' | grep -E '^(ntfy-|umami-|nomadro-|deploy-nsq)' | xargs -r docker stop; " + "free -m | head -2", + t=90, +) +run("sync; echo 1 > /proc/sys/vm/drop_caches 2>/dev/null; free -m | head -2") + +# revive API — may be crashed but unit active zombie +run( + "systemctl reset-failed douyinweb-api douyinweb-web 2>/dev/null; " + "systemctl restart douyinweb-api; sleep 4; " + "systemctl restart douyinweb-web; sleep 3; " + "systemctl is-active douyinweb-api douyinweb-web caddy; " + "ss -lntp | grep -E ':4015|:8014|:443' | head -10", + t=120, +) +run( + "curl -sS -m 8 -o /dev/null -w 'w:%{http_code}\\n' http://127.0.0.1:4015/youtube; " + "curl -sS -m 8 -o /dev/null -w 'a:%{http_code}\\n' http://127.0.0.1:8014/api/health; " + "curl -sS -m 10 -o /dev/null -w 'pub:%{http_code}\\n' -H 'Host: dylive.nomadro.com' " + "http://127.0.0.1/youtube || true; " + "free -m | head -2; uptime", + t=60, +) +c.close() +print("DONE") diff --git a/scripts/_emergency_revive2.py b/scripts/_emergency_revive2.py new file mode 100644 index 0000000..b6af7ca --- /dev/null +++ b/scripts/_emergency_revive2.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Aggressive revive: kill docker/neko, free RAM, start caddy+api+web for real.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print("ssh", i, flush=True) + return c + except Exception as ex: + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=120): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print((out[-6000:] if len(out) > 6000 else out) or f"(empty {code})", flush=True) + return code + + +c = ssh() + +# What eats RAM? +run(c, "ps aux --sort=-%mem | head -20; echo ---; timeout 15 docker ps -a --format '{{.Names}} {{.Status}}' 2>/dev/null | head -30; echo ---; free -h; uptime", 50) + +# Hard stop all docker containers +run( + c, + "timeout 60 docker stop $(timeout 20 docker ps -q) 2>/dev/null; " + "timeout 30 docker kill $(timeout 15 docker ps -q) 2>/dev/null; " + "echo DOCKER_DOWN; free -h | head -2; uptime", + 150, +) + +# Kill leftover chrome / next zombies if any +run( + c, + "pkill -9 chrome 2>/dev/null; pkill -9 chromium 2>/dev/null; " + "pkill -9 -f 'next-server|uvicorn app.main' 2>/dev/null; " + "sleep 2; free -h | head -2; uptime", + 40, +) + +# Start only what dylive+edge need, with longer TimeoutStart for caddy +run( + c, + "mkdir -p /etc/systemd/system/caddy.service.d; " + "printf '[Service]\\nTimeoutStartSec=180\\n' > /etc/systemd/system/caddy.service.d/timeout.conf; " + "systemctl daemon-reload; " + "systemctl reset-failed caddy douyinweb-api douyinweb-web 2>/dev/null; " + "systemctl start seaweed-master seaweed-volume seaweed-filer seaweed-s3 2>/dev/null; " + "systemctl start douyinweb-pb douyinweb-yt; " + "systemctl start douyinweb-api; sleep 3; " + "systemctl start douyinweb-web; sleep 3; " + "systemctl start caddy nginx frpp; sleep 3; " + "systemctl is-active caddy nginx frpp douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "ss -lntp | grep -E ':(443|80|8014|4015|4014|8092|8020|8333)\\b' || true", + 200, +) + +run( + c, + "curl -sS -m 10 http://127.0.0.1:8014/api/health; echo; " + "curl -sS -m 10 -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/; " + "curl -sS -m 10 -o /dev/null -w 'caddy_local=%{http_code}\\n' -k https://127.0.0.1/ -H 'Host: dylive.nomadro.com'; " + "journalctl -u caddy -n 25 --no-pager; " + "journalctl -u douyinweb-api -n 20 --no-pager", + 60, +) + +# WG again +run(c, "wg-quick down wg-dy 2>/dev/null; wg-quick up wg-dy; sleep 3; wg show wg-dy | head -18; ping -c 2 -W 2 10.8.0.2 | tail -3", 40) + +c.close() +print("DONE", flush=True) diff --git a/scripts/_emergency_stop_neko_revive.py b/scripts/_emergency_stop_neko_revive.py new file mode 100644 index 0000000..e08d569 --- /dev/null +++ b/scripts/_emergency_stop_neko_revive.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Emergency: stop all Neko on VPS to free RAM, then bring dylive + frpp + wg back.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(tries=10): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print(f"ssh ok {i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"retry {i} {ex}", flush=True) + time.sleep(3) + raise SystemExit(str(last)) + + +def run(c, cmd, t=90): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print((out[-5000:] if len(out) > 5000 else out) or f"(empty {code})", flush=True) + return code + + +c = ssh() + +# Stop every neko container NOW (biggest RAM eaters) +run( + c, + "uptime; free -h | head -2; " + "timeout 40 docker ps -aq --filter name=douyinweb-neko | xargs -r docker stop -t 2; " + "timeout 40 docker ps -aq --filter name=neko | xargs -r docker stop -t 2; " + "echo NEKO_STOPPED; free -h | head -2; uptime", + 120, +) + +# Drop other heavy leftovers if any chrome outside docker +run( + c, + "pkill -9 -f 'google-chrome|chromium|chromedriver' 2>/dev/null || true; " + "sleep 2; free -h | head -2; uptime", + 30, +) + +# Bring core services +run( + c, + "systemctl restart frpp; " + "systemctl restart douyinweb-pb; " + "systemctl restart douyinweb-yt; " + "systemctl restart douyinweb-api; " + "systemctl restart douyinweb-web; " + "systemctl restart caddy; " + "sleep 5; " + "systemctl is-active frpp caddy douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "ss -lntp | grep -E ':8014|:4015|:443|:4014|:8092|:8020' || true; " + "curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 220; echo; " + "curl -sS -m 8 -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/", + 120, +) + +# WG +run( + c, + "wg-quick down wg-dy 2>/dev/null; wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -15; " + "ss -lntp | grep -E '4014|7000|7500|frp' || true; " + "systemctl is-active frpp", + 45, +) + +c.close() +print("DONE_EMERGENCY", flush=True) diff --git a/scripts/_ensure_dylive_tm_seed.py b/scripts/_ensure_dylive_tm_seed.py new file mode 100644 index 0000000..9d10c6c --- /dev/null +++ b/scripts/_ensure_dylive_tm_seed.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Re-apply TM seed on dylive if path broken; confirm seed markers.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) +_i, o, e = c.exec_command( + r""" +set +e +SEED='/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +GOOD='/opt/douyinWEB/backend/data/neko/profiles/2/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +echo -n 'seed_exists='; [ -d "$SEED" ] && echo yes || echo no +echo -n 'seed_markers='; grep -a -R -c 'YouTube Studio Auto Dismiss' "$SEED" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}' +echo -n 'good_markers='; grep -a -R -c 'YouTube Studio Auto Dismiss' "$GOOD" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}' +if ! grep -a -R -q 'YouTube Studio Auto Dismiss' "$SEED" 2>/dev/null; then + echo 'refreshing seed from profile 2' + mkdir -p "$(dirname "$SEED")" + rm -rf "$SEED" + cp -a "$GOOD" "$SEED" + rm -f "$SEED/LOCK" +fi +echo -n 'seed_markers_after='; grep -a -R -c 'YouTube Studio Auto Dismiss' "$SEED" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +docker exec douyinweb-neko-2 python3 -c "import os,re;p='/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo';b=b''.join(open(os.path.join(r,f),'rb').read() for r,_,fs in os.walk(p) for f in fs);print('neko2', 'OK' if b'YouTube Studio Auto Dismiss' in b else 'EMPTY', len(b))" +curl -sS -m 5 -o /dev/null -w 'public_neko2:%{http_code}\n' https://dylive.nomadro.com/neko/2/ +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fill_dylive_new_slots.py b/scripts/_fill_dylive_new_slots.py new file mode 100644 index 0000000..ff4b9f1 --- /dev/null +++ b/scripts/_fill_dylive_new_slots.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Add pool urls into slots for newly synced time_slot groups on dylive.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", i, e) + time.sleep(2) + raise SystemExit("fail") + + +c = ssh("107.173.30.245") +_i, o, e = c.exec_command( + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +for name in ('china street food', 'nice street food'): + g = next((x for x in yt_assign_db.list_groups(include_urls=True, include_secret=False) if x.get('name')==name), None) + if not g: + print('missing', name); continue + gid = g['id'] + slots = g.get('slots') or [] + pool = g.get('pool') or [] + print(name, 'slots_before', len(slots), 'pool', len(pool)) + if slots: + print(' already has slots'); continue + ids = [p['id'] for p in pool if p.get('id')] + if not ids: + print(' no pool ids'); continue + print(' add_slot', yt_assign_db.add_slot(gid, ids)) + g2 = yt_assign_db.get_group(gid, include_secret=False) + print(' slots_after', len(g2.get('slots') or []), 'cat', g2.get('category')) + +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +print('assign', len(gs), 'full', sum(1 for g in gs if len(str(g.get('stream_key')or''))>=12)) +from app import yt_stream_key_db +print('registry', yt_stream_key_db.list_entries()['total']) +PY +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +docker exec douyinweb-neko-12 supervisorctl status google-chrome | head -1 +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_find_good_tm_les.py b/scripts/_find_good_tm_les.py new file mode 100644 index 0000000..4157f13 --- /dev/null +++ b/scripts/_find_good_tm_les.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Find a working TM LES on physical and clone into ops-neko 1/2 + seed.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +echo "=== scan assign + ops profiles on host ===" +for root in /opt/douyinWEB/backend/data/neko/profiles /opt/douyinWEB/backend/data/ops_neko/profiles; do + [ -d "$root" ] || continue + for d in "$root"/*; do + [ -d "$d" ] || continue + hit=$(grep -aR -l "YouTube Studio Auto Dismiss" "$d" 2>/dev/null | head -1) + if [ -n "$hit" ]; then + echo FOUND "$d" -> "$hit" + du -sh "$d/Default/Local Extension Settings/$EXT" 2>/dev/null || true + fi + done +done +echo "=== seed LES ===" +SEED=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/$EXT +du -sh "$SEED" 2>/dev/null || echo no_seed_les +grep -aR "YouTube Studio Auto Dismiss" "$SEED" 2>/dev/null | head -1 || echo seed_has_no_script + +# Also check running assign containers +for id in 1 2 3 4 5 6 7 8; do + name=douyinweb-neko-$id + if docker ps --format "{{.Names}}" | grep -qx "$name"; then + h=$(docker exec "$name" bash -lc "grep -aR -l \"YouTube Studio Auto Dismiss\" /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT 2>/dev/null | head -1") + if [ -n "$h" ]; then echo FOUND_CONTAINER "$name"; fi + fi +done +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_find_neko_profile.py b/scripts/_find_neko_profile.py new file mode 100644 index 0000000..c4c95a9 --- /dev/null +++ b/scripts/_find_neko_profile.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +import paramiko + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r''' +docker inspect douyinweb-neko-12 --format '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}' | grep -iE 'chrome|chromium|profile' +echo '---' +find /opt/douyinWEB -maxdepth 4 -type d -name 'profiles' 2>/dev/null +ls -la /var/lib/douyinweb-neko 2>/dev/null | head +python3 - <<'PY' +import sys +sys.path.insert(0,'/opt/douyinWEB/backend') +from app import youtube_neko +print('neko_root', youtube_neko._neko_root()) +print('profile12', youtube_neko._ensure_profile(12)) +PY +''' +_, o, e = c.exec_command(cmd, timeout=30) +print((o.read()+e.read()).decode()) +c.close() diff --git a/scripts/_find_nomadro_next.py b/scripts/_find_nomadro_next.py new file mode 100644 index 0000000..a8f9e90 --- /dev/null +++ b/scripts/_find_nomadro_next.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Find nomadro.com Next.js vs WordPress on VPS (read-only).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +echo '=== systemd nomadro / next / node ===' +systemctl list-unit-files --no-pager 2>/dev/null | grep -iE 'nomadro|next|wordpress|wp-|httpd|nginx' || true +systemctl list-units --all --type=service --no-pager 2>/dev/null | grep -iE 'nomadro|next|wordpress|wp-|caddy|nginx' || true +echo '=== /opt /var/www candidates ===' +ls -la /opt 2>/dev/null | head -60 +ls -la /var/www 2>/dev/null | head -40 +ls -d /opt/* /var/www/* /home/*/www* /home/*/nomadro* 2>/dev/null | head -80 +echo '=== package.json with nomadro or next ===' +find /opt /var/www /home -maxdepth 4 -name package.json 2>/dev/null | head -40 +echo '=== caddy nomadro.com ===' +grep -RIn --include='*.caddy' --include='Caddyfile*' 'nomadro.com' /etc/caddy 2>/dev/null | grep -v 'dy\.nomadro\|dylive\|book\|s3\|wx\|ro' | head -40 +ls /etc/caddy/sites 2>/dev/null +echo '=== docker ===' +docker ps -a --format '{{.Names}} {{.Status}} {{.Image}}' 2>/dev/null | grep -iE 'nomadro|wordpress|wp|next' || true +echo '=== pm2 / screen ===' +command -v pm2 >/dev/null && pm2 list || echo no-pm2 +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_find_nomadro_next.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_find_nomadro_next.sh", timeout=90) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_finish_dy_covers_setting.py b/scripts/_finish_dy_covers_setting.py new file mode 100644 index 0000000..b20e86b --- /dev/null +++ b/scripts/_finish_dy_covers_setting.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +cd /opt/douyinWEB/backend +timeout 45 ./.venv/bin/python - <<'PY' +from app import db +db.update_settings_map({"covers_s3_keep_days": 2}) +print("covers_s3_keep_days=", db.get_settings_map().get("covers_s3_keep_days")) +PY +systemctl restart douyinweb-api +sleep 3 +echo api=$(systemctl is-active douyinweb-api) +df -h / | awk 'NR==2{print}' +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err.strip(): + print("[stderr]", err[:1000]) +c.close() diff --git a/scripts/_finish_dy_migrate.py b/scripts/_finish_dy_migrate.py new file mode 100644 index 0000000..d65d986 --- /dev/null +++ b/scripts/_finish_dy_migrate.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Finish dy post-migrate: public_base, neko mem, nginx neko locations.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +cmd = r""" +set -euo pipefail +# Ensure public base in env for neko nginx sync +grep -q '^DY_PUBLIC_BASE_URL=' /etc/douyinweb.env \ + && sed -i 's|^DY_PUBLIC_BASE_URL=.*|DY_PUBLIC_BASE_URL=https://dy.nomadro.live|' /etc/douyinweb.env \ + || echo 'DY_PUBLIC_BASE_URL=https://dy.nomadro.live' >> /etc/douyinweb.env +grep -q '^PUBLIC_BASE=' /etc/douyinweb.env \ + && sed -i 's|^PUBLIC_BASE=.*|PUBLIC_BASE=https://dy.nomadro.live|' /etc/douyinweb.env \ + || echo 'PUBLIC_BASE=https://dy.nomadro.live' >> /etc/douyinweb.env + +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_PUBLIC_BASE_URL=https://dy.nomadro.live +export DY_NEKO_NAT1TO1=108.174.50.68 + +./.venv/bin/python - <<'PY' +from app import db +from app import youtube_neko as yn +from app import config + +db.update_settings_map({ + 'neko_mem_limit': '1536m', +}) +print('public', config.settings.public_base_url or '(empty-settings-obj)') +print('env_public', __import__('os').environ.get('DY_PUBLIC_BASE_URL')) +# Force regenerate nginx include for /neko/1..4 +r = yn.sync_nginx_proxy(4) +print('sync_nginx', r) +inc = '/etc/nginx/conf.d/douyinweb-neko-locations.inc' +import pathlib +p = pathlib.Path(inc) +print('inc_exists', p.exists(), 'lines', len(p.read_text().splitlines()) if p.exists() else 0) +# count neko locations +txt = p.read_text() if p.exists() else '' +print('neko_locs', txt.count('location ^~ /neko/')) +PY + +nginx -t +systemctl reload nginx +systemctl restart douyinweb-api +sleep 2 + +# verify +curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/l.json -w 'login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \ + -H 'Content-Type: application/json' -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/l.json; echo +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db, shorts_oauth +sm=db.get_settings_map() +print('cookie', len(str(sm.get('dy_cookie') or ''))) +print('mem', sm.get('neko_mem_limit')) +print('redirect', sm.get('shorts_oauth_redirect_uri')) +for p in shorts_oauth.normalize_oauth_profiles(sm.get('shorts_oauth_profiles')): + print(p['id'], 'ok' if p.get('client_id') and p.get('client_secret') else 'empty', (p.get('label') or '')[:40]) +rooms=db.list_rooms() +print('rooms', rooms.get('total') if isinstance(rooms, dict) else len(rooms)) +PY +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +print("exit", o.channel.recv_exit_status()) +c.close() diff --git a/scripts/_finish_dylive_local_neko.py b/scripts/_finish_dylive_local_neko.py new file mode 100644 index 0000000..95c1359 --- /dev/null +++ b/scripts/_finish_dylive_local_neko.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Finish dylive local neko after port remap (wait for API).""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + return c + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:180]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-10000:] if len(out) > 10000 else out, flush=True) + return code, out + + +c = ssh() +run( + c, + r""" +set +e +echo '--- units ---' +systemctl is-active dy-frp-http-aux caddy douyinweb-api douyinweb-web +echo '--- frp-aux forwards ---' +grep -oE '127.0.0.1:[0-9]+' /etc/systemd/system/dy-frp-http-aux.service | head -40 +echo '--- caddy neko1 proxy ---' +grep -A2 'handle_path /neko/1/\*' /etc/caddy/sites/dy.nomadro.com.caddy | head -8 +echo '--- who owns 9200/19200 ---' +ss -lntp | grep -E ':(920[0-7]|1920[0-7])\b' | head -20 +echo '--- NAT1TO1 env ---' +systemctl show douyinweb-api -p Environment --value | tr ' ' '\n' | grep NEKO +# wait api +for i in $(seq 1 30); do + curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && echo api_up_$i && break + sleep 1 +done +curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 200; echo +# ensure host_profile deployed +python3 -c 'from app import host_profile; print(host_profile.status()["effects"]["vps"])' 2>/dev/null || \ + (cd /opt/douyinWEB/backend && /opt/douyinWEB/.venv/bin/python -c 'import sys; sys.path.insert(0,"."); from app import host_profile; print(host_profile.status()["effects"]["vps"])') +""", + 90, +) + +run( + c, + r""" +set +e +# if api down, restart +systemctl is-active douyinweb-api || systemctl restart douyinweb-api +sleep 2 +for i in $(seq 1 40); do + curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break + sleep 1 +done +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' +echo +GID=$(curl -sS -m 20 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups | python3 -c ' +import sys,json +rows=json.load(sys.stdin) +rows=rows if isinstance(rows,list) else rows.get("groups") or [] +for g in rows: + if int(g.get("neko_instance_id") or 0)==3: + print(g.get("id") or ""); break +') +echo gid=$GID +curl -sS -m 180 -b "$CS" -X POST "http://127.0.0.1:8014/api/youtube/assign/groups/${GID}/neko" \ + -H 'Content-Type: application/json' \ + -d '{"action":"start","enabled":true}' | tee /tmp/neko_start3.json | python3 -c ' +import sys,json +d=json.load(sys.stdin) +print("keys", list(d)[:12]) +n=d.get("neko") or {} +print("neko", {k:n.get(k) for k in ("id","running","ready","status","studio_url","detail")}) +g=d.get("group") or {} +print("enabled", g.get("neko_enabled"), "err", d.get("detail") or d.get("error")) +' +sleep 3 +docker ps --format '{{.Names}} {{.Status}}' | grep douyinweb-neko | head +ss -lntp | grep -E ':(9202|19200)\b' | head +curl -sS -m 10 -o /dev/null -w 'local9202=%{http_code}\n' http://127.0.0.1:9202/ +curl -sS -m 10 -o /dev/null -w 'aux19200=%{http_code}\n' http://127.0.0.1:19200/ +docker inspect douyinweb-neko-3 --format '{{json .Config.Env}}' 2>/dev/null | tr ',' '\n' | grep -E 'NAT1TO1|BITRATE|MAX_FPS|DESKTOP_SCREEN|BROWSER_PROXY|START_URL' || echo no_container +rm -f "$CS" +""", + 220, +) +c.close() + +print("\n===== public =====", flush=True) +with httpx.Client(follow_redirects=False, timeout=25) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/neko/3/", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + ]: + try: + r = cl.get(u) + print(f"{r.status_code} {u}", flush=True) + except Exception as ex: + print(f"ERR {u} {ex}", flush=True) +print("DONE", flush=True) diff --git a/scripts/_finish_dylive_recv_only.py b/scripts/_finish_dylive_recv_only.py new file mode 100644 index 0000000..434fca4 --- /dev/null +++ b/scripts/_finish_dylive_recv_only.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Finish dylive half only — chunked SFTP with progress (no silent hang).""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +HOST = "107.173.30.245" +LOCAL_HASH = { + "backend/app/douyin.py": hashlib.sha256( + (ROOT / "backend/app/douyin.py").read_bytes() + ).hexdigest()[:12], + "frontend/src/components/YtRelayProStatusPanel.tsx": hashlib.sha256( + (ROOT / "frontend/src/components/YtRelayProStatusPanel.tsx").read_bytes() + ).hexdigest()[:12], +} + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + print(f"ssh {HOST} try {i}...", flush=True) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=90, + ) + print("ssh ok", flush=True) + return c + except Exception as e: + print(f"ssh fail: {e}", flush=True) + time.sleep(1 + i) + raise SystemExit("ssh_fail") + + +def put_progress(sftp, local: Path, remote: str): + size = local.stat().st_size + print(f"upload {local.name} ({size/1e6:.1f}MB) -> {remote}", flush=True) + last = [0.0] + + def cb(sent, total): + now = time.time() + if now - last[0] >= 2.0 or sent == total: + pct = 100.0 * sent / total if total else 0 + print(f" {local.name}: {pct:.0f}% ({sent/1e6:.1f}/{total/1e6:.1f}MB)", flush=True) + last[0] = now + + sftp.put(str(local), remote, callback=cb) + print(f" {local.name}: done", flush=True) + + +def run(c, cmd, timeout=180): + print(f"$ {cmd[:100]}...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + start = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.recv_stderr_ready(): + sys.stdout.write(chan.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.15) + code = chan.recv_exit_status() + print(f"\n[exit {code}]", flush=True) + return code + + +print("local hashes:", LOCAL_HASH, flush=True) +c = connect() +sftp = c.open_sftp() +put_progress(sftp, ROOT / "scripts/_src-recv-fix.tgz", "/tmp/src-recv-fix.tgz") +put_progress(sftp, ROOT / "scripts/_next-recv-fix.tgz", "/tmp/next-recv-fix.tgz") +sftp.close() + +code = run( + c, + r""" +set -e +tar -C /opt/douyinWEB -xzf /tmp/src-recv-fix.tgz +systemctl restart douyinweb-api +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_recv +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_recv 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-recv-fix.tgz +systemctl start douyinweb-web +sleep 2 +echo api=$(systemctl is-active douyinweb-api) web=$(systemctl is-active douyinweb-web) +python3 - <<'PY' +import hashlib, pathlib +for rel in ['backend/app/douyin.py','frontend/src/components/YtRelayProStatusPanel.tsx']: + p=pathlib.Path('/opt/douyinWEB')/rel + print('hash', hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel) +PY +grep -n 'YouTube 接流中\|推流接流' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -5 +""", + timeout=180, +) +c.close() +if code != 0: + raise SystemExit(f"dylive_fail {code}") +print("ALL_DONE", LOCAL_HASH, flush=True) diff --git a/scripts/_finish_ops_live_gate.py b/scripts/_finish_ops_live_gate.py new file mode 100644 index 0000000..08484f4 --- /dev/null +++ b/scripts/_finish_ops_live_gate.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Finish VPS API restart + force-open Live tabs on ops-neko 1/2.""" +import sys +import time +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + v = paramiko.SSHClient() + v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("VPS restart…", flush=True) + # non-blocking-ish + v.exec_command("systemctl restart douyinweb-api >/tmp/api_rst.log 2>&1 &", timeout=15) + time.sleep(8) + _i, o, e = v.exec_command( + "systemctl is-active douyinweb-api; " + "grep -c wait_group_ready_for_live /opt/douyinWEB/backend/app/youtube_relay_pipeline.py", + timeout=30, + ) + print((o.read() + e.read()).decode(), flush=True) + v.close() + + p = paramiko.SSHClient() + p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = p.open_sftp() + with sftp.file("/tmp/_force_ops_live.py", "wb") as f: + f.write( + b""" +import sys, json +sys.path.insert(0, "/opt/douyinWEB/backend") +from app import ops_neko, ops_neko_db +print("role", ops_neko_db.peer_status()) +print("instances", [{k: r.get(k) for k in ("slot","name","want_running","bind_remote_group_id")} for r in ops_neko_db.list_instances()]) +cards = ops_neko.pull_remote_cards() +print("cards_ok", cards.get("ok"), "n", len(cards.get("cards") or []), "err", cards.get("error")) +for c in (cards.get("cards") or []): + if c.get("ops_neko_slot") or c.get("neko_open_prefer")=="remote": + print(" card", c.get("name"), "slot", c.get("ops_neko_slot"), "prefer", c.get("neko_open_prefer"), "yt", c.get("youtube_channel_id")) +# force both slots +for slot in (1, 2): + yt = "" + for c in (cards.get("cards") or []): + if int(c.get("ops_neko_slot") or 0) == slot: + yt = str(c.get("youtube_channel_id") or "") + break + print("ensure", slot, ops_neko.ensure_slot_live_studio(slot, youtube_channel_id=yt)) +print("bound_pass", ops_neko.ensure_bound_slots_live_studio()) +print("catalog", ops_neko.push_catalog_to_hub()) +""" + ) + sftp.close() + _i, o, e = p.exec_command( + "echo 4669805 | sudo -S -p '' bash -lc '" + "cd /opt/douyinWEB/backend; " + "PY=python3; [ -x .venv/bin/python ] && PY=.venv/bin/python; " + "$PY /tmp/_force_ops_live.py" + "'", + timeout=180, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + p.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_finish_phys_neko_tm.py b/scripts/_finish_phys_neko_tm.py new file mode 100644 index 0000000..31ecf57 --- /dev/null +++ b/scripts/_finish_phys_neko_tm.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Finish physical Neko TM soft-seed + ensure Chrome running (no docker cp).""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SEED_PY = r''' +import json, shutil +from pathlib import Path +EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo" +SEED=Path("/etc/neko/tampermonkey-seed/Default") + +def load(p): + try: return json.loads(p.read_text(encoding="utf-8")) + except Exception: return {} + +def has_dismiss(p: Path) -> bool: + if not p.is_dir(): return False + for f in p.iterdir(): + if f.is_file() and f.stat().st_size: + try: + if b"YouTube Studio Auto Dismiss" in f.read_bytes(): + return True + except Exception: + pass + return False + +def seed_one(base: Path): + base.mkdir(parents=True, exist_ok=True) + seed_ext = SEED/"Extensions"/EXT + if not seed_ext.exists(): + print("NO_SEED_EXT"); return + dst = base/"Extensions"/EXT + if dst.exists(): + shutil.rmtree(dst, ignore_errors=True) + (base/"Extensions").mkdir(parents=True, exist_ok=True) + shutil.copytree(seed_ext, dst) + mf = dst/"5.5.0_0"/"manifest.json" + if mf.exists(): + md=load(mf); md.pop("update_url", None) + mf.write_text(json.dumps(md, ensure_ascii=False, indent=3)+"\n", encoding="utf-8") + les = base/"Local Extension Settings"/EXT + seed_les = SEED/"Local Extension Settings"/EXT + if has_dismiss(les): + print("les_keep") + elif seed_les.exists() and has_dismiss(seed_les): + if les.exists(): + shutil.rmtree(les, ignore_errors=True) + (base/"Local Extension Settings").mkdir(parents=True, exist_ok=True) + shutil.copytree(seed_les, les) + for lock in list(les.glob("LOCK")): + lock.unlink(missing_ok=True) + print("les_seeded") + else: + print("les_skip") + seed_entry=((load(SEED/"Preferences").get("extensions") or {}).get("settings") or {}).get(EXT) or {} + entry=dict(seed_entry) if isinstance(seed_entry, dict) else {} + entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False}) + entry.pop("disable_reasons", None) + mf2=entry.get("manifest") + if isinstance(mf2, dict): + mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2 + pref=base/"Preferences" + d=load(pref) if pref.exists() else {} + d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry) + d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True + pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8") + print("ok", base) + +for b in (Path("/home/neko/.config/google-chrome/Default"), Path("/home/neko/.config/chromium/Default")): + if b.parent.exists() or True: + try: + seed_one(b) + except Exception as ex: + print("fail", b, ex) +print("DONE") +''' + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_seed_tm_soft2.py", "w") as f: + f.write(SEED_PY) + sftp.close() + + # upload seed script to host then pipe into each container via tee (avoid docker cp RO bug) + cmd = r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +NAMES=$(docker ps --format "{{.Names}}" | grep -E "^douyinweb-(neko|ops-neko)-[0-9]+$" | sort) +echo "names: $NAMES" +for name in $NAMES; do + echo "===== $name =====" + docker exec "$name" supervisorctl stop google-chrome 2>/dev/null || true +done +sleep 2 +for name in $NAMES; do + echo "===== SEED $name =====" + docker exec -i "$name" tee /tmp/_seed_tm_soft2.py >/dev/null < /tmp/_seed_tm_soft2.py + docker exec "$name" python3 /tmp/_seed_tm_soft2.py + docker exec "$name" supervisorctl start google-chrome || docker exec "$name" supervisorctl restart google-chrome + docker exec "$name" supervisorctl status google-chrome +done +sleep 12 +for name in $NAMES; do + echo "===== VERIFY $name =====" + docker exec "$name" python3 -c " +import json +from pathlib import Path +ext=\"dhdgffkkebhmkfjojejmpbldmpobfkfo\" +base=Path(\"/home/neko/.config/google-chrome/Default\") +e=((json.loads((base/\"Preferences\").read_text()).get(\"extensions\") or {}).get(\"settings\") or {}).get(ext) or {}) +print(\"tm\", e.get(\"state\"), e.get(\"location\"), e.get(\"path\")) +print(\"ext\", (base/\"Extensions\"/ext/\"5.5.0_0\"/\"manifest.json\").exists()) +les=base/\"Local Extension Settings\"/ext +hit=False +if les.is_dir(): + for f in les.iterdir(): + if f.is_file() and f.stat().st_size: + try: + if b\"YouTube Studio Auto Dismiss\" in f.read_bytes(): + hit=True; break + except Exception: pass +print(\"dismiss\", hit, \"cookies\", (base/\"Cookies\").stat().st_size if (base/\"Cookies\").exists() else -1) +" +done +echo FINISH_OK +' +""" + print("running...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + with httpx.Client(timeout=20) as cl: + for u in [ + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/7/", + "https://dy.nomadro.cn/ops-neko/1/", + "https://dy.nomadro.cn/neko/1/", + ]: + try: + print(cl.get(u).status_code, u, flush=True) + except Exception as ex: + print("ERR", u, ex, flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_finish_recv_panel_deploy_live.py b/scripts/_finish_recv_panel_deploy_live.py new file mode 100644 index 0000000..20e6377 --- /dev/null +++ b/scripts/_finish_recv_panel_deploy_live.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Finish receiving-first panel deploy with live prints (no silent wait).""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +FILES = [ + ("backend/app/douyin.py", "c1a660fcf8f8"), # expected may drift; we recompute + ("frontend/src/components/YtRelayProStatusPanel.tsx", ""), +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + last = None + for i in range(10): + try: + print(f"ssh {host} try {i}...", flush=True) + c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False, banner_timeout=90) + print(f"ssh {host} ok", flush=True) + return c + except Exception as e: + last = e + print(f"ssh fail: {e}", flush=True) + time.sleep(1 + i) + raise SystemExit(f"ssh_fail {host}: {last}") + + +def run_stream(c, cmd, timeout=900): + print(f"$ {cmd[:120]}...", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True) + chan = o.channel + start = time.time() + buf = b"" + while True: + if chan.recv_ready(): + chunk = chan.recv(4096) + if not chunk: + break + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + if chan.recv_stderr_ready(): + chunk = chan.recv_stderr(4096) + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + chunk = chan.recv(4096) + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > timeout: + print("TIMEOUT", flush=True) + break + time.sleep(0.2) + code = chan.recv_exit_status() + print(f"\n[exit {code}]", flush=True) + return code + + +def put(c, local: Path, remote: str): + print(f"put {local.name} -> {remote}", flush=True) + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + sftp.close() + + +# hashes +hashes = {} +for rel, _ in FILES: + p = ROOT / rel.replace("/", "\\") + h = hashlib.sha256(p.read_bytes()).hexdigest()[:12] + hashes[rel] = h + print(f"local {h} {rel}", flush=True) + +# --- DY --- +print("\n=== DY ===", flush=True) +c = connect("108.174.50.68") +# kill stuck npm if any from previous deploy +run_stream( + c, + "pkill -f 'npm run build' 2>/dev/null || true; pkill -f 'next build' 2>/dev/null || true; echo cleaned; " + "ps aux | grep -E 'npm|next' | grep -v grep | head -5 || true", + timeout=30, +) +for rel, _ in FILES: + put(c, ROOT / rel.replace("/", "\\"), f"/opt/douyinWEB/{rel}") + +code = run_stream( + c, + r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python -c "from app.douyin import pick_stream_candidates; r={'stream_url':{'flv_pull_url':{'ORIGIN':'http://x/a_uhd.flv','HD1':'http://x/a_hd.flv'}}}; assert 'a_hd' in pick_stream_candidates(r)[0]; print('non_uhd_ok')" +grep -n 'YouTube 接流中\|推流接流' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -8 +systemctl restart douyinweb-api +echo api=$(systemctl is-active douyinweb-api) +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build +systemctl restart douyinweb-web +echo web=$(systemctl is-active douyinweb-web) +tar -C /opt/douyinWEB/frontend -czf /tmp/next-recv-fix.tgz .next +tar -C /opt/douyinWEB -czf /tmp/src-recv-fix.tgz backend/app/douyin.py frontend/src/components/YtRelayProStatusPanel.tsx +ls -lh /tmp/next-recv-fix.tgz /tmp/src-recv-fix.tgz +""", + timeout=700, +) +if code != 0: + raise SystemExit(f"dy_build_failed {code}") + +print("fetch tarballs...", flush=True) +sftp = c.open_sftp() +sftp.get("/tmp/next-recv-fix.tgz", str(ROOT / "scripts/_next-recv-fix.tgz")) +sftp.get("/tmp/src-recv-fix.tgz", str(ROOT / "scripts/_src-recv-fix.tgz")) +sftp.close() +c.close() +print("dy done", flush=True) + +# --- DYLIVE --- +print("\n=== DYLIVE ===", flush=True) +c = connect("107.173.30.245") +put(c, ROOT / "scripts/_src-recv-fix.tgz", "/tmp/src-recv-fix.tgz") +put(c, ROOT / "scripts/_next-recv-fix.tgz", "/tmp/next-recv-fix.tgz") +run_stream( + c, + r""" +set -e +tar -C /opt/douyinWEB -xzf /tmp/src-recv-fix.tgz +systemctl restart douyinweb-api +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_recv +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_recv 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-recv-fix.tgz +systemctl start douyinweb-web +sleep 2 +echo api=$(systemctl is-active douyinweb-api) web=$(systemctl is-active douyinweb-web) +python3 - <<'PY' +import hashlib, pathlib +for rel in ['backend/app/douyin.py','frontend/src/components/YtRelayProStatusPanel.tsx']: + p=pathlib.Path('/opt/douyinWEB')/rel + print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel) +PY +grep -n 'YouTube 接流中\|推流接流' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -5 +""", + timeout=120, +) +c.close() + +print("\nALL_DONE", flush=True) +for rel, h in hashes.items(): + print(f"shipped {h} {rel}", flush=True) diff --git a/scripts/_finish_shorts_frontload_pace.py b/scripts/_finish_shorts_frontload_pace.py new file mode 100644 index 0000000..a3dbaee --- /dev/null +++ b/scripts/_finish_shorts_frontload_pace.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +"""Finish FE build + pull-forward parked Shorts slots (venv-aware).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r'''#!/bin/bash +set -euo pipefail +cd /opt/douyinWEB +if [ -f .venv/bin/activate ]; then . .venv/bin/activate; fi +if [ -f venv/bin/activate ]; then . venv/bin/activate; fi +if [ -f backend/.venv/bin/activate ]; then . backend/.venv/bin/activate; fi +echo "python=$(command -v python || true)" +python -c "import pydantic_settings; print('pydantic_ok')" +cd /opt/douyinWEB/backend +python <<'PY' +import sys, sqlite3, time, datetime +sys.path.insert(0, "/opt/douyinWEB/backend") +from app.shorts_schedule import fleet_pace_plan, pull_forward_due_uploads +plan = fleet_pace_plan() +keys = ( + "uploaded", "front_target", "need_front", "behind", "urgent", + "recommended_global_gap_sec", "recommended_channel_gap_sec", "recommended_per_hour", +) +print("pace", {k: plan.get(k) for k in keys}) +print("pulled", pull_forward_due_uploads()) +BJ = datetime.timezone(datetime.timedelta(hours=8)) +now = time.time() +day = datetime.datetime.now(BJ).strftime("%Y-%m-%d") +con = sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +due = fut = 0 +hours = {} +q = ( + "SELECT upload_at FROM shorts_jobs WHERE push_date=? " + "AND status IN ('scheduled','recorded') AND IFNULL(clip_path,'')!=''" +) +for (ua0,) in con.execute(q, (day,)): + ua = float(ua0 or 0) + if ua <= now + 90: + due += 1 + else: + fut += 1 + if ua > 0: + h = datetime.datetime.fromtimestamp(ua, BJ).hour + hours[h] = hours.get(h, 0) + 1 +print("due_now", due, "future", fut, "by_hour", dict(sorted(hours.items()))) +con.close() +PY +cd /opt/douyinWEB/frontend +npm run build 2>&1 | tail -20 +systemctl restart douyinweb-web.service +sleep 3 +systemctl is-active douyinweb-web.service +''' + + +def run(label: str, host: str, port: int, user: str, pw: str, *, sudo: bool) -> None: + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dy_pace_finish.sh", "w") as f: + f.write(SCRIPT.replace("\r\n", "\n")) + sftp.close() + cmd = ( + f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_pace_finish.sh" + if sudo + else "bash /tmp/_dy_pace_finish.sh" + ) + _, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +run("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +run("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_finish_studio_state_deploy.py b/scripts/_finish_studio_state_deploy.py new file mode 100644 index 0000000..9b98626 --- /dev/null +++ b/scripts/_finish_studio_state_deploy.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Finish deploy: wait VPS API + sudo tee on physical.""" +from __future__ import annotations + +import base64 +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = [ + "backend/app/youtube_neko.py", + "backend/app/youtube_relay_pipeline.py", + "backend/app/ops_neko.py", + "backend/neko/cdp_studio_scrape.py", + "backend/neko/live-ops-extension/content.js", +] + + +def run(c, cmd, t=90): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return f"ERR {type(ex).__name__}: {ex}" + + +def main(): + # VPS + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + print("VPS active:", run(c, "systemctl is-active douyinweb-api", 15).strip()) + for i in range(12): + h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x", 10).strip() + print(f" health try{i}", h) + if h == "200": + break + if i == 0: + print(run(c, "systemctl restart douyinweb-api", 40).strip()) + time.sleep(3) + # marker check + print( + "VPS marker", + run( + c, + "grep -c encoder_lost /opt/douyinWEB/backend/app/youtube_neko.py /opt/douyinWEB/backend/neko/cdp_studio_scrape.py /opt/douyinWEB/backend/neko/live-ops-extension/content.js", + 15, + ).strip(), + ) + c.close() + + # Physical via sudo tee + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=30, allow_agent=False, look_for_keys=False) + for rel in FILES: + data = (ROOT / rel).read_bytes() + b64 = base64.b64encode(data).decode("ascii") + remote = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" + # write via sudo bash -c with base64 + cmd = ( + f"echo {b64} | base64 -d | sudo tee {remote} >/dev/null && " + f"sudo chmod 644 {remote} && echo OK {remote}" + ) + print(run(c, cmd, 40).strip()) + print( + run( + c, + r""" +sudo systemctl restart douyinweb-api 2>/dev/null || sudo systemctl restart douyinweb 2>/dev/null || true +sleep 3 +systemctl is-active douyinweb-api 2>/dev/null; systemctl is-active douyinweb 2>/dev/null +curl -sS -m 5 -o /dev/null -w 'health=%{http_code}\n' http://127.0.0.1:8014/api/health || true +# sync scrape into ops-neko-1 +for i in 1 2; do + n=douyinweb-ops-neko-$i + docker inspect $n >/dev/null 2>&1 || continue + sudo docker cp /opt/douyinWEB/backend/neko/cdp_studio_scrape.py $n:/etc/neko/cdp_studio_scrape.py 2>/dev/null || true + sudo docker cp /opt/douyinWEB/backend/neko/live-ops-extension/content.js $n:/etc/neko/live-ops-extension/content.js 2>/dev/null || true +done +# classify now +sudo docker exec douyinweb-ops-neko-1 python3 /etc/neko/cdp_studio_scrape.py 2>/dev/null | tail -1 | head -c 900 +""", + 70, + ) + ) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_finish_vps_yt_long_quota.py b/scripts/_finish_vps_yt_long_quota.py new file mode 100644 index 0000000..a8ed217 --- /dev/null +++ b/scripts/_finish_vps_yt_long_quota.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + for cmd, t in [ + ("systemctl restart douyinweb-api", 90), + ("sleep 3; systemctl is-active douyinweb-api; curl -sS -m 10 -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health", 40), + ]: + print("$", cmd, flush=True) + _, o, e = c.exec_command(cmd, timeout=t) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + py = r""" +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +print('login', op.open(req, timeout=20).status) +req2=urllib.request.Request('http://127.0.0.1:8014/api/yt-long/settings', data=json.dumps({'yt_long_channel_daily_max': 8}).encode(), headers={'Content-Type':'application/json'}, method='POST') +r=json.loads(op.open(req2, timeout=40).read()) +print('save', r.get('settings',{}).get('yt_long_channel_daily_max'), r.get('channel_daily_max')) +st=json.loads(op.open('http://127.0.0.1:8014/api/yt-long/status', timeout=40).read()) +print('status', st.get('settings',{}).get('yt_long_channel_daily_max'), st.get('channel_daily_max')) +""" + sftp = c.open_sftp() + with sftp.file("/tmp/_v_ylq2.py", "w") as f: + f.write(py) + sftp.close() + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python /tmp/_v_ylq2.py", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_fix_all_assign_chrome_dual.py b/scripts/_fix_all_assign_chrome_dual.py new file mode 100644 index 0000000..9eea83f --- /dev/null +++ b/scripts/_fix_all_assign_chrome_dual.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Kill orphan chrome in all physical assign Nekos; single clean restart each.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +FIX = r"""#!/bin/bash +set -e +for i in 1 2 3 4 5 6 7 8; do + N=douyinweb-neko-$i + docker inspect "$N" >/dev/null 2>&1 || continue + echo "===== $N =====" + docker exec "$N" supervisorctl stop google-chrome || true + sleep 1 + docker exec -i "$N" python3 - <<'PY' +import os, signal, time +killed=[] +for _ in range(3): + for pid in list(os.listdir("/proc")): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw or b"/opt/google/chrome" in raw: + try: + os.kill(int(pid), signal.SIGKILL) + killed.append(pid) + except Exception: + pass + time.sleep(0.4) +print("killed", len(killed)) +PY + docker exec "$N" bash -lc 'rm -f /home/neko/.config/google-chrome/SingletonCookie /home/neko/.config/google-chrome/SingletonLock /home/neko/.config/google-chrome/SingletonSocket /home/neko/.config/google-chrome/SingletonStartupLock /home/neko/.config/google-chrome/lockfile /home/neko/.config/google-chrome/DevToolsActivePort 2>/dev/null; true' + docker exec "$N" supervisorctl start google-chrome +done +echo '===== wait =====' +sleep 22 +for i in 1 2 3 4 5 6 7 8; do + N=douyinweb-neko-$i + docker inspect "$N" >/dev/null 2>&1 || continue + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1 +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw}") +PY +) + echo "neko-$i $out" +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_all_assign_chrome_dual.sh", "w") as f: + f.write(FIX) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_fix_all_assign_chrome_dual.sh", + timeout=300, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_clear_missing_avatars.py b/scripts/_fix_clear_missing_avatars.py new file mode 100644 index 0000000..abe3db6 --- /dev/null +++ b/scripts/_fix_clear_missing_avatars.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Blank missing avatar_url so UI falls back to /api/sessions/.../cover.""" +from __future__ import annotations + +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +PASS = "Xiao4669805" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +SCRIPT = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request + +def exists(url: str) -> bool: + try: + urllib.request.urlopen(url, timeout=4).read(8) + return True + except Exception: + return False + +with _lock: + conn = _connect() + rows = conn.execute( + "SELECT id, avatar_url FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url != ''" + ).fetchall() + cleared = kept = 0 + for rid, u in rows: + u = str(u or "").strip() + if not u.startswith("http"): + continue + if exists(u): + kept += 1 + continue + conn.execute("UPDATE rooms SET avatar_url='' WHERE id=?", (rid,)) + cleared += 1 + # pool covers pointing at dead hosts + try: + for a in ( + "https://dy.nomadro.com/douyin-covers%", + ): + cur = conn.execute( + "UPDATE yt_assign_pool_urls SET cover_url='' WHERE cover_url LIKE ?", + (a,), + ) + print("pool_cleared_dycom", cur.rowcount) + except Exception as e: + print("pool", e) + conn.commit() + print("avatar_kept", kept, "avatar_cleared", cleared) +PY +""" + +for label, host in HOSTS: + print(f"######## {label} ########", flush=True) + c = connect(host) + _i, o, e = c.exec_command(SCRIPT, timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dual_neko_panel_parity.py b/scripts/_fix_dual_neko_panel_parity.py new file mode 100644 index 0000000..02f610f --- /dev/null +++ b/scripts/_fix_dual_neko_panel_parity.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Verify dual VPS source parity + explain Neko panel state diff.""" +from __future__ import annotations + +import hashlib +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +PASS = "Xiao4669805" +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] + +FILES = [ + "backend/app/douyin.py", + "backend/app/session_auth.py", + "backend/app/youtube_neko.py", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/lib/api.js", + "frontend/src/components/YtAssignPanel.tsx", +] + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail " + host) + + +def run(c, cmd, timeout=120): + _i, o, e = c.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put(c, data: bytes, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(data) + sftp.close() + + +local = {} +print("LOCAL", flush=True) +for rel in FILES: + p = ROOT / rel.replace("/", "\\") + h = hashlib.sha256(p.read_bytes()).hexdigest()[:12] + local[rel] = h + print(h, rel, flush=True) + +remote_hashes = {} +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + c = connect(host) + out = run( + c, + "python3 - <<'PY'\n" + "import hashlib, pathlib\n" + f"files={FILES!r}\n" + "root=pathlib.Path('/opt/douyinWEB')\n" + "for rel in files:\n" + " p=root/rel\n" + " print(('MISSING' if not p.exists() else hashlib.sha256(p.read_bytes()).hexdigest()[:12]), rel)\n" + "PY\n" + "echo '--- panel markers ---'\n" + "grep -n '双 VPS\\|Live 页\\|本机 Neko 数据\\|物理机' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -20\n" + "echo '--- next build ---'\n" + "stat -c '%y' /opt/douyinWEB/frontend/.next/BUILD_ID 2>/dev/null || echo no_build_id\n" + "echo '--- neko docker ---'\n" + "docker ps --filter name=neko --format '{{.Names}} {{.Status}}' 2>/dev/null\n", + ) + print(out, flush=True) + remote_hashes[label] = {} + for line in out.splitlines(): + parts = line.strip().split(None, 1) + if len(parts) == 2 and parts[1] in local: + remote_hashes[label][parts[1]] = parts[0] + c.close() + +print("\n=== HASH DIFF vs LOCAL ===", flush=True) +need_sync = False +for label, hm in remote_hashes.items(): + for rel, lh in local.items(): + rh = hm.get(rel, "MISSING") + ok = rh == lh + if not ok: + need_sync = True + print(f"{label:7} {'OK' if ok else 'DIFF'} {rel} local={lh} remote={rh}", flush=True) + +# Force sync if any DIFF +if need_sync: + print("\n=== FORCE SYNC BOTH ===", flush=True) + # Build src tar locally conceptually by uploading each file + for label, host in HOSTS: + c = connect(host) + for rel in FILES: + p = ROOT / rel.replace("/", "\\") + put(c, p.read_bytes(), f"/opt/douyinWEB/{rel}") + print("put", label, rel, flush=True) + print( + run( + c, + r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.douyin import pick_stream_candidates +room={"stream_url":{"flv_pull_url":{"ORIGIN":"http://x/a_uhd.flv","HD1":"http://x/a_hd.flv"}}} +assert 'a_hd.flv' in pick_stream_candidates(room)[0] +print('douyin_pick_ok') +PY +systemctl restart douyinweb-api +sleep 1 +systemctl is-active douyinweb-api +""", + timeout=60, + ), + flush=True, + ) + c.close() + + # FE: build on dy, sync .next to dylive + print("=== FE build on dy + sync ===", flush=True) + c = connect("108.174.50.68") + print( + run( + c, + r""" +set -e +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build 2>&1 | tail -20 +systemctl restart douyinweb-web +tar -C /opt/douyinWEB/frontend -czf /tmp/next-panel-sync.tgz .next +ls -lh /tmp/next-panel-sync.tgz +""", + timeout=700, + ), + flush=True, + ) + sftp = c.open_sftp() + sftp.get("/tmp/next-panel-sync.tgz", str(ROOT / "scripts/_next-panel-sync.tgz")) + sftp.close() + c.close() + + c = connect("107.173.30.245") + put(c, (ROOT / "scripts/_next-panel-sync.tgz").read_bytes(), "/tmp/next-panel-sync.tgz") + print( + run( + c, + r""" +set -e +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_panel +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_panel 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-panel-sync.tgz +systemctl start douyinweb-web +sleep 2 +systemctl is-active douyinweb-web +""", + timeout=90, + ), + flush=True, + ) + c.close() + +# API studio/neko state comparison for focused groups +print("\n=== RUNTIME STATE (not source) ===", flush=True) + + +def login_opener(site): + cj = CookieJar() + opener = urllib.request.build_opener( + urllib.request.HTTPSHandler(context=CTX), + urllib.request.HTTPCookieProcessor(cj), + ) + body = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + site + "/api/auth/login", + data=body, + headers={"Content-Type": "application/json"}, + method="POST", + ) + with opener.open(req, timeout=30) as r: + r.read() + return opener + + +for site in ("https://dylive.nomadro.com", "https://dy.nomadro.live"): + print(f"\n--- {site} ---", flush=True) + try: + op = login_opener(site) + with op.open(site + "/api/youtube/assign/groups", timeout=40) as r: + groups = json.loads(r.read().decode()).get("groups") or [] + # find nomad street food / nice street food + for g in groups: + name = str(g.get("name") or "") + if "street" not in name.lower() and "Street" not in name: + continue + print( + { + "name": name, + "neko_id": g.get("neko_instance_id"), + "neko_enabled": g.get("neko_enabled"), + "prefer": g.get("neko_open_prefer") or g.get("ops_neko_prefer"), + }, + flush=True, + ) + nid = int(g.get("neko_instance_id") or 0) + if nid: + try: + with op.open(site + f"/api/youtube/neko/{nid}/status", timeout=20) as r: + st = json.loads(r.read().decode()) + print(" neko_status", {k: st.get(k) for k in ("running", "ready", "url", "error", "container")}, flush=True) + except Exception as e: + print(" neko_status_err", e, flush=True) + # studio samples / status endpoint variants + for path in ( + "/api/youtube/studio/samples", + "/api/youtube/assign/studio-status", + "/api/youtube/relay/status", + ): + try: + with op.open(site + path, timeout=25) as r: + data = json.loads(r.read().decode()) + if path.endswith("relay/status"): + ents = data.get("entries") or data.get("items") or [] + if isinstance(ents, list): + for e in ents[:8]: + if not isinstance(e, dict): + continue + if e.get("is_pushing") or str(e.get("status") or "").find("push") >= 0: + print(" relay", {k: e.get(k) for k in ("name", "group_id", "status", "is_pushing", "source_url")}, flush=True) + else: + print(path, "keys", list(data.keys())[:12] if isinstance(data, dict) else type(data), flush=True) + except Exception as e: + print(path, "ERR", e, flush=True) + except Exception as e: + print("SITE_ERR", e, flush=True) + +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dual_vps_s3_images.py b/scripts/_fix_dual_vps_s3_images.py new file mode 100644 index 0000000..7c421ba --- /dev/null +++ b/scripts/_fix_dual_vps_s3_images.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Fix dual-VPS S3 public images for dylive.nomadro.com + dy.nomadro.live.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + +DYLIVE = "107.173.30.245" +DY = "108.174.50.68" +PASS = "Xiao4669805" + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, script: str, timeout=180) -> str: + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put(c, local_bytes: bytes, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(local_bytes) + sftp.close() + + +def http_code(url: str) -> str: + try: + req = urllib.request.Request(url, headers={"User-Agent": "fix"}) + with urllib.request.urlopen(req, timeout=20, context=CTX) as r: + return f"{r.status} {r.headers.get('content-type','')}" + except urllib.error.HTTPError as e: + return f"HTTP {e.code}" + except Exception as ex: + return f"ERR {ex}" + + +# --- 1) Fix dy VPS (108.174.50.68): anonymous S3 + nginx /douyin-covers --- +print("######## FIX dy VPS 108.174.50.68 ########", flush=True) +c_dy = connect(DY) +print( + run( + c_dy, + r""" +set -e +echo '=== nginx sites with douyin / covers ===' +ls /etc/nginx/sites-enabled /etc/nginx/conf.d 2>/dev/null +grep -RniE 'dy\.nomadro\.live|douyin-covers|8333|covers|proxy_pass' /etc/nginx 2>/dev/null | head -60 +echo +echo '=== current s3.json ===' +python3 - <<'PY' +import json +p='/etc/seaweedfs/douyinweb-s3.json' +print(open(p).read()[:800]) +PY +""", + ), + flush=True, +) + +# Apply anonymous read + backup +print(run(c_dy, r""" +set -e +CFG=/etc/seaweedfs/douyinweb-s3.json +cp -a "$CFG" "${CFG}.bak.$(date +%Y%m%d%H%M%S)" +python3 - <<'PY' +import json +p='/etc/seaweedfs/douyinweb-s3.json' +d=json.load(open(p)) +idents=d.get('identities') or [] +# ensure anonymous Read +anon=None +for i in idents: + if i.get('name')=='anonymous': + anon=i + break +if anon is None: + idents.insert(0, {'name':'anonymous','actions':['Read']}) +else: + acts=set(anon.get('actions') or []) + acts.add('Read') + anon['actions']=sorted(acts) +d['identities']=idents +json.dump(d, open(p,'w'), indent=2) +print('wrote', p) +print(json.dumps(d, indent=2)[:1200]) +PY +systemctl restart douyinweb-s3.service +sleep 1 +systemctl is-active douyinweb-s3.service +# anonymous GET smoke +curl -sS -m 5 -o /dev/null -w 'anon:%{http_code}\n' \ + 'http://127.0.0.1:8333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg' || true +"""), flush=True) + +# nginx: ensure /douyin-covers proxies to local S3 +print(run(c_dy, r""" +set -e +# find server block for dy.nomadro.live +CONF=$(grep -Rl 'dy.nomadro.live' /etc/nginx 2>/dev/null | head -1) +echo conf=$CONF +if [ -z "$CONF" ]; then + echo 'NO_NGINX_CONF' + exit 0 +fi +cp -a "$CONF" "${CONF}.bak.s3fix.$(date +%Y%m%d%H%M%S)" +python3 - <<'PY' +import pathlib, re, time +conf=pathlib.Path(""" + '"$(grep -Rl dy.nomadro.live /etc/nginx 2>/dev/null | head -1)"' + r""") +# above injection messy — redo in shell heredoc properly +PY +"""), flush=True) +c_dy.close() + +# Cleaner nginx patch via dedicated remote script +c_dy = connect(DY) +nginx_fix = r'''#!/bin/bash +set -euo pipefail +CONF=$(grep -Rl 'server_name.*dy.nomadro.live' /etc/nginx 2>/dev/null | head -1 || true) +if [ -z "$CONF" ]; then + CONF=$(grep -Rl 'dy.nomadro.live' /etc/nginx 2>/dev/null | head -1 || true) +fi +echo "CONF=$CONF" +if [ -z "$CONF" ]; then + echo "MISSING_CONF"; exit 2 +fi +cp -a "$CONF" "${CONF}.bak.s3fix.$(date +%Y%m%d%H%M%S)" +python3 - "$CONF" <<'PY' +import pathlib, sys, re +p = pathlib.Path(sys.argv[1]) +text = p.read_text(encoding="utf-8", errors="replace") +block = """ + location /douyin-covers/ { + proxy_pass http://127.0.0.1:8333; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_hide_header x-amz-id-2; + proxy_hide_header x-amz-request-id; + } +""" +if "location /douyin-covers/" in text: + # replace existing location block roughly + text2, n = re.subn( + r"location\s+/douyin-covers/\s*\{[\s\S]*?\n\s*\}", + block.strip(), + text, + count=1, + ) + if n: + text = text2 + print("replaced existing /douyin-covers location") + else: + print("found marker but regex miss; appending before last } of file carefully") + # insert before last closing brace of server — fallback: after server_name line + text = text.replace("server_name", block + "\n server_name", 1) +else: + # insert after first server_name line inside file + if "server_name" in text: + text = text.replace("server_name", block + "\n server_name", 1) + print("inserted /douyin-covers after server_name") + else: + raise SystemExit("cannot find insertion point") +p.write_text(text, encoding="utf-8") +print("patched", p) +PY +nginx -t +systemctl reload nginx +echo nginx_reloaded +# public local via nginx +curl -sS -m 5 -o /dev/null -w 'nginx_local_s3:%{http_code}\n' \ + -H 'Host: dy.nomadro.live' \ + 'http://127.0.0.1/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg' || true +''' +put(c_dy, nginx_fix.encode(), "/tmp/fix_dy_nginx_s3.sh") +print(run(c_dy, "bash /tmp/fix_dy_nginx_s3.sh"), flush=True) + +# Also bind S3 to 0.0.0.0 so peer VPS can reach if needed? User said both VPS - for dy.nomadro.com on dylive, +# better point Caddy to this host's public IP:8333 OR use SSH tunnel. +# Prefer: change dylive Caddy /douyin-covers -> 127.0.0.1:8333 (local anonymous bucket shares many avatars) +# AND rewrite dy.nomadro.com avatars that 404 to try s3 — but first check object presence. + +# For now also open seaweed bind to 0.0.0.0 on dy so dylive can proxy to 108.174.50.68:8333 +print(run(c_dy, r""" +set -e +UNIT=/etc/systemd/system/douyinweb-s3.service +cp -a "$UNIT" "${UNIT}.bak.$(date +%Y%m%d%H%M%S)" +# change -ip.bind=127.0.0.1 to 0.0.0.0 if present +sed -i 's/-ip.bind=127.0.0.1/-ip.bind=0.0.0.0/g' "$UNIT" +systemctl daemon-reload +systemctl restart douyinweb-s3.service +sleep 1 +systemctl is-active douyinweb-s3.service +ss -lntp | grep 8333 || true +# firewall? allow from dylive only if ufw +if command -v ufw >/dev/null; then ufw status | head -20; fi +# iptables quick allow 8333 from dylive if needed — check listen first +curl -sS -m 3 -o /dev/null -w 'local_anon:%{http_code}\n' 'http://127.0.0.1:8333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg' +"""), flush=True) +c_dy.close() + +# --- 2) Fix dylive Caddy: /douyin-covers -> local 8333 (same as s3.nomadro.com) --- +# Avatars historically on dy.nomadro.com; many objects also on s3.nomadro.com. +# Additionally reverse_proxy to dy VPS public :8333 as fallback is hard in Caddy without rewrite. +# Strategy: point dy.nomadro.com /douyin-covers to 108.174.50.68:8333 (peer VPS S3 now public bind) +print("######## FIX dylive Caddy dy.nomadro.com ########", flush=True) +c_v = connect(DYLIVE) +print(run(c_v, r""" +set -e +CFG=/etc/caddy/sites/dy.nomadro.com.caddy +cp -a "$CFG" "${CFG}.bak.s3fix.$(date +%Y%m%d%H%M%S)" +python3 - <<'PY' +from pathlib import Path +p=Path('/etc/caddy/sites/dy.nomadro.com.caddy') +text=p.read_text(encoding='utf-8') +old='reverse_proxy 127.0.0.1:28333' +# Prefer peer dy VPS S3 (where avatar objects for dy.nomadro.com historically lived). +# Fallback local VPS S3 also has anonymous read for objects mirrored there. +new='reverse_proxy 108.174.50.68:8333' +if old in text: + text=text.replace(old, new) + print('replaced 28333 -> 108.174.50.68:8333') +elif 'handle /douyin-covers/*' in text: + import re + text2,n=re.subn( + r'(handle /douyin-covers/\* \{\n\s*reverse_proxy )[^\n]+', + r'\g<1>108.174.50.68:8333', + text, + count=1, + ) + if n: + text=text2 + print('regex replaced douyin-covers upstream') + else: + raise SystemExit('could not patch douyin-covers') +else: + raise SystemExit('no douyin-covers block') +# Host header: Seaweed virtual-host style — keep Host as dy.nomadro.com or use s3 style. +# Path-style /douyin-covers/... needs Host that seaweed accepts; previously Host {host}. +p.write_text(text, encoding='utf-8') +print('ok') +PY +# show snippet +grep -nA3 'douyin-covers' /etc/caddy/sites/dy.nomadro.com.caddy | head -20 +caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20 +systemctl reload caddy +echo caddy_reloaded +# probe peer S3 from this host +curl -sS -m 8 -o /dev/null -w 'peer_s3:%{http_code}\n' \ + 'http://108.174.50.68:8333/douyin-covers/covers/avatars/16693589495.jpg' || echo peer_fail +curl -sS -m 8 -o /dev/null -w 'local_s3_avatar:%{http_code}\n' \ + 'http://127.0.0.1:8333/douyin-covers/covers/avatars/16693589495.jpg' || true +"""), flush=True) + +# Deploy session_auth fix to both +auth_local = open(r"c:\Users\admin\Desktop\douyinWEB\backend\app\session_auth.py", "rb").read() +for label, host in [("dylive", DYLIVE), ("dy", DY)]: + print(f"######## deploy session_auth -> {label} ########", flush=True) + c = connect(host) + put(c, auth_local, "/opt/douyinWEB/backend/app/session_auth.py") + print( + run( + c, + r""" +set -e +grep -n 'covers/' /opt/douyinWEB/backend/app/session_auth.py | head -10 +systemctl restart douyinweb-api +sleep 2 +systemctl is-active douyinweb-api +# pick a cover file if any +F=$(ls /opt/douyinWEB/backend/data/covers/*.jpg 2>/dev/null | head -1 || true) +if [ -n "$F" ]; then + BN=$(basename "$F") + curl -sS -m 5 -o /dev/null -w "covers_noauth:%{http_code}\n" "http://127.0.0.1:8014/covers/$BN" +fi +""", + ), + flush=True, + ) + c.close() + +# --- public verify --- +print("######## PUBLIC VERIFY ########", flush=True) +urls = [ + "https://s3.nomadro.com/douyin-covers/covers/avatars/193393415810.jpg", + "https://dy.nomadro.com/douyin-covers/covers/avatars/16693589495.jpg", + "https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg", + "https://dy.nomadro.live/douyin-covers/covers/avatars/690114366322.jpg", + "https://dylive.nomadro.com/api/sessions/b9197cd9-b9af-432f-8e2a-880370ce75da/cover", + "https://dy.nomadro.live/api/sessions/ab13d4f5-9639-40db-a40f-6af8443f3757/cover", +] +for u in urls: + print(http_code(u), u, flush=True) + +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dual_vps_s3_images2.py b/scripts/_fix_dual_vps_s3_images2.py new file mode 100644 index 0000000..0660e96 --- /dev/null +++ b/scripts/_fix_dual_vps_s3_images2.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Finish S3 image fix: nginx dedupe, Caddy local S3, rewrite avatar hosts, verify.""" +from __future__ import annotations + +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail " + host) + + +def run(c, script, timeout=120): + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def code(url): + try: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "v"}), timeout=20, context=CTX) as r: + return f"{r.status}" + except urllib.error.HTTPError as e: + return f"HTTP{e.code}" + except Exception as ex: + return f"ERR:{type(ex).__name__}" + + +# 1) Fix nginx on dy: remove duplicate inserted block, ensure one good location +print("=== fix nginx dy ===", flush=True) +c = connect(DY) +print(run(c, r""" +set -e +CONF=/etc/nginx/conf.d/dy-nomadro-live.conf +# restore from bak.covers or bak.s3fix earliest good, then patch cleanly +ls -lt ${CONF}.bak* 2>/dev/null | head -10 +# Prefer bak.covers if present (known prior state), else newest bak.s3fix before our bad insert +if [ -f ${CONF}.bak.covers ]; then + cp -a ${CONF}.bak.covers ${CONF}.frombak + echo using bak.covers +elif ls ${CONF}.bak.s3fix.* >/dev/null 2>&1; then + # first bak created by our script is pre-insert + FIRST=$(ls -1t ${CONF}.bak.s3fix.* | tail -1) + cp -a "$FIRST" ${CONF}.frombak + echo using $FIRST +else + cp -a "$CONF" ${CONF}.frombak +fi +python3 - <<'PY' +from pathlib import Path +import re +src=Path('/etc/nginx/conf.d/dy-nomadro-live.conf.frombak') +dst=Path('/etc/nginx/conf.d/dy-nomadro-live.conf') +text=src.read_text(encoding='utf-8', errors='replace') +# strip any existing /douyin-covers locations +text2=re.sub(r"\n\s*location\s+/douyin-covers/\s*\{[\s\S]*?\n\s*\}", "\n", text) +block=''' + location /douyin-covers/ { + proxy_http_version 1.1; + proxy_pass http://127.0.0.1:8333; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + } +''' +# insert inside first server { after server_name line +m=re.search(r"(server_name\s+[^;]+;)", text2) +if not m: + raise SystemExit('no server_name') +ins=m.end() +text2=text2[:ins]+"\n"+block+text2[ins:] +dst.write_text(text2, encoding='utf-8') +print('wrote clean nginx conf') +# count locations +print('loc_count', text2.count('location /douyin-covers/')) +PY +nginx -t +systemctl reload nginx +echo nginx_ok +curl -sS -m 5 -o /dev/null -w 'https_cover:%{http_code}\n' https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg || true +"""), flush=True) + +# rewrite avatar hosts in DB on dy +print(run(c, r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +repls=[ + ('https://dy.nomadro.com/douyin-covers','https://s3.nomadro.com/douyin-covers'), + ('http://dy.nomadro.com/douyin-covers','https://s3.nomadro.com/douyin-covers'), +] +with _lock: + conn=_connect() + total=0 + for a,b in repls: + cur=conn.execute("SELECT COUNT(*) FROM rooms WHERE avatar_url LIKE ?", (a+'%',)) + n=cur.fetchone()[0] + if n: + conn.execute("UPDATE rooms SET avatar_url=REPLACE(avatar_url, ?, ?) WHERE avatar_url LIKE ?", (a,b,a+'%')) + total+=n + print('rooms', a, '->', b, n) + # also pool covers if any + try: + for a,b in repls: + cur=conn.execute("SELECT COUNT(*) FROM yt_assign_pool_urls WHERE cover_url LIKE ?", (a+'%',)) + n=cur.fetchone()[0] + if n: + conn.execute("UPDATE yt_assign_pool_urls SET cover_url=REPLACE(cover_url, ?, ?) WHERE cover_url LIKE ?", (a,b,a+'%')) + print('pool', a, n) + except Exception as e: + print('pool_skip', e) + conn.commit() + print('rewrote_rooms', total) + # sample + for r in conn.execute("SELECT substr(avatar_url,1,100) FROM rooms WHERE avatar_url LIKE 'http%' LIMIT 5"): + print('sample', r[0]) +PY +"""), flush=True) +c.close() + +# 2) dylive: Caddy point to local S3; rewrite DB avatars +print("=== fix dylive caddy+db ===", flush=True) +c = connect(DYLIVE) +print(run(c, r""" +set -e +CFG=/etc/caddy/sites/dy.nomadro.com.caddy +# point to local seaweed (s3.nomadro.com backend) — both VPS; avatars rewritten to s3 host anyway +python3 - <<'PY' +from pathlib import Path +import re +p=Path('/etc/caddy/sites/dy.nomadro.com.caddy') +text=p.read_text(encoding='utf-8') +text2,n=re.subn( + r'(handle /douyin-covers/\* \{\n\s*reverse_proxy )[^\s{]+', + r'\g<1>127.0.0.1:8333', + text, + count=1, +) +print('n', n) +if not n: + raise SystemExit('patch fail') +p.write_text(text2, encoding='utf-8') +print(Path('/etc/caddy/sites/dy.nomadro.com.caddy').read_text().split('douyin-covers')[1][:200]) +PY +caddy validate --config /etc/caddy/Caddyfile >/tmp/caddyval.out 2>&1 || true +tail -3 /tmp/caddyval.out +systemctl reload caddy +echo caddy_ok +"""), flush=True) + +print(run(c, r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +repls=[ + ('https://dy.nomadro.com/douyin-covers','https://s3.nomadro.com/douyin-covers'), + ('http://dy.nomadro.com/douyin-covers','https://s3.nomadro.com/douyin-covers'), + ('https://dy.nomadro.live/douyin-covers','https://s3.nomadro.com/douyin-covers'), +] +with _lock: + conn=_connect() + for a,b in repls: + n=conn.execute("SELECT COUNT(*) FROM rooms WHERE avatar_url LIKE ?", (a+'%',)).fetchone()[0] + if n: + conn.execute("UPDATE rooms SET avatar_url=REPLACE(avatar_url, ?, ?) WHERE avatar_url LIKE ?", (a,b,a+'%')) + print('rooms', a, n) + try: + for a,b in repls: + n=conn.execute("SELECT COUNT(*) FROM yt_assign_pool_urls WHERE cover_url LIKE ?", (a+'%',)).fetchone()[0] + if n: + conn.execute("UPDATE yt_assign_pool_urls SET cover_url=REPLACE(cover_url, ?, ?) WHERE cover_url LIKE ?", (a,b,a+'%')) + print('pool', a, n) + except Exception as e: + print('pool_skip', e) + conn.commit() + for r in conn.execute("SELECT substr(avatar_url,1,110) FROM rooms WHERE avatar_url LIKE 'http%' LIMIT 6"): + print('sample', r[0]) + # existence probe via local s3 for first 8 avatars + import urllib.request + rows=conn.execute("SELECT avatar_url FROM rooms WHERE avatar_url LIKE 'https://s3.nomadro.com/%' LIMIT 12").fetchall() + ok=bad=0 + for (u,) in rows: + key=u.split('douyin-covers/',1)[-1] + try: + code=urllib.request.urlopen('http://127.0.0.1:8333/douyin-covers/'+key, timeout=3).status + ok+=1 + except Exception: + bad+=1 + print('missing', u[-60:]) + print('s3_probe_ok', ok, 'bad', bad) +PY +"""), flush=True) +c.close() + +# 3) FE fallback: if avatar 404, browsers still blank — improve sessionCoverSrc to prefer cover when +# avatar host historically broken. Safer: keep s3 rewrite; add small FE onerror is heavier deploy. +# Also ensure dylive DY_S3_PUBLIC_BASE stays s3.nomadro.com for new uploads. + +print("=== public verify ===", flush=True) +urls = [ + "https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg", + "https://s3.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg", + "https://s3.nomadro.com/douyin-covers/covers/avatars/288944177940.jpg", + "https://dy.nomadro.com/douyin-covers/covers/avatars/288944177940.jpg", + "https://dylive.nomadro.com/api/sessions/b9197cd9-b9af-432f-8e2a-880370ce75da/cover", + "https://dy.nomadro.live/api/sessions/ab13d4f5-9639-40db-a40f-6af8443f3757/cover", +] +for u in urls: + print(code(u), u, flush=True) + +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dual_vps_s3_images3.py b/scripts/_fix_dual_vps_s3_images3.py new file mode 100644 index 0000000..ab9a771 --- /dev/null +++ b/scripts/_fix_dual_vps_s3_images3.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Fix nginx include dupes; check avatar existence on dy S3; align public_base.""" +from __future__ import annotations + +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, script, timeout=120): + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== dy nginx full conf + includes ===", flush=True) +c = connect(DY) +print(run(c, r""" +set -e +CONF=/etc/nginx/conf.d/dy-nomadro-live.conf +echo '---- current conf ----' +nl -ba "$CONF" | sed -n '1,120p' +echo +echo '---- includes mentioning covers ----' +grep -RniE 'douyin-covers|covers' /etc/nginx 2>/dev/null | head -40 +"""), flush=True) + +# Fix: strip ALL douyin-covers from main conf and from bak, write ONE block; also check includes +print(run(c, r""" +set -e +python3 - <<'PY' +from pathlib import Path +import re +p=Path('/etc/nginx/conf.d/dy-nomadro-live.conf') +# start from bak.covers OR current +cands=[Path('/etc/nginx/conf.d/dy-nomadro-live.conf.bak.covers'), p] +text=None +for c in cands: + if c.exists(): + text=c.read_text(encoding='utf-8', errors='replace') + print('base', c) + break +# remove ALL location /douyin-covers/ blocks +while True: + text2,n=re.subn(r"\n[ \t]*location\s+/douyin-covers/[^{]*\{(?:[^{}]|\{[^{}]*\})*\}", "\n", text, count=1) + if not n: + break + text=text2 + print('removed one block') +# also remove our botched insert that might be malformed +text=re.sub(r"\n[ \t]*location\s+/douyin-covers/[\s\S]*?\n[ \t]*\}\n", "\n", text) +block=''' + location /douyin-covers/ { + proxy_http_version 1.1; + proxy_pass http://127.0.0.1:8333; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + } +''' +if text.count('location /douyin-covers/')!=0: + print('STILL HAS', text.count('location /douyin-covers/')) + # nuke lines containing douyin-covers location start through matching braces manually + lines=text.splitlines(True) + out=[]; i=0 + while i < len(lines): + if re.search(r'location\s+/douyin-covers/', lines[i]): + # skip until brace balance 0 + bal=0; started=False + while i < len(lines): + bal += lines[i].count('{') - lines[i].count('}') + started=True + i+=1 + if started and bal<=0: + break + continue + out.append(lines[i]); i+=1 + text=''.join(out) +print('after strip count', text.count('location /douyin-covers/')) +m=re.search(r"(server_name\s+[^;]+;)", text) +if not m: + raise SystemExit('no server_name') +text=text[:m.end()]+"\n"+block+text[m.end():] +p.write_text(text, encoding='utf-8') +print('final count', text.count('location /douyin-covers/')) +PY +# if include file also has it, comment out +for f in /etc/nginx/conf.d/*.inc /etc/nginx/conf.d/*covers* ; do + [ -f "$f" ] || continue + if grep -q 'location /douyin-covers' "$f" 2>/dev/null; then + echo "FOUND in $f — commenting" + sed -i 's/^\(\s*location \/douyin-covers\)/# \1/' "$f" || true + fi +done +nginx -t +systemctl reload nginx +echo nginx_reloaded_ok +"""), flush=True) + +# Probe avatars on local dy S3 vs s3.nomadro (via listing a few from DB) +print(run(c, r""" +set -e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request +with _lock: + conn=_connect() + rows=conn.execute("SELECT avatar_url FROM rooms WHERE avatar_url LIKE 'https://s3.nomadro.com/%' LIMIT 20").fetchall() +ok=bad=[] +for (u,) in rows: + key=u.split('https://s3.nomadro.com/douyin-covers/',1)[-1] + local='http://127.0.0.1:8333/douyin-covers/'+key + try: + urllib.request.urlopen(local, timeout=3).read(16) + ok.append(key) + except Exception as e: + bad.append(key) +print('dy_local_ok', len(ok), 'bad', len(bad)) +print('ok_sample', ok[:5]) +print('bad_sample', bad[:8]) +# if many ok on dy local but missing on s3.nomadro, point avatar_url to dy.nomadro.live +PY +# Also set DY_S3_PUBLIC_BASE to dy.nomadro.live so new uploads get working host +grep -n S3_PUBLIC /etc/systemd/system/douyinweb-api.service /etc/douyinweb.env 2>/dev/null | head +"""), flush=True) +c.close() + +# If dy local has avatars that s3 doesn't, rewrite avatar base to https://dy.nomadro.live/douyin-covers +print("=== maybe rewrite to dy.nomadro.live if objects live there ===", flush=True) +c = connect(DY) +out = run(c, r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request +with _lock: + conn=_connect() + rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'https://s3.nomadro.com/douyin-covers/%'").fetchall() +moved=0 +keep=0 +missing_both=0 +for rid, u in rows: + key=u.split('https://s3.nomadro.com/douyin-covers/',1)[-1] + on_dy=False + on_s3=False + try: + urllib.request.urlopen('http://127.0.0.1:8333/douyin-covers/'+key, timeout=2).read(8) + on_dy=True + except Exception: + pass + # don't call remote s3 from here for all — use on_dy preference + if on_dy: + new='https://dy.nomadro.live/douyin-covers/'+key + conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid)) + moved+=1 + else: + missing_both+=1 +conn.commit() +print('moved_to_dy_live', moved, 'not_on_dy', missing_both) +for r in conn.execute("SELECT substr(avatar_url,1,100), COUNT(*) FROM rooms WHERE avatar_url LIKE 'http%' GROUP BY 1 LIMIT 5"): + pass +from collections import Counter +c=Counter() +for (u,) in conn.execute("SELECT CASE WHEN avatar_url LIKE 'https://dy.nomadro.live%' THEN 'dy.live' WHEN avatar_url LIKE 'https://s3.nomadro.com%' THEN 's3' ELSE 'other' END FROM rooms WHERE avatar_url LIKE 'http%'"): + c[u]+=1 +print(dict(c)) +PY +""") +print(out, flush=True) +c.close() + +# Sync same rewrite logic on dylive DB: for each avatar, if not on local s3, point to dy.nomadro.live +c = connect(DYLIVE) +print(run(c, r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request +with _lock: + conn=_connect() + rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'http%'").fetchall() +to_live=to_s3=missing=0 +for rid,u in rows: + u=str(u) + if '/douyin-covers/' not in u: + continue + key=u.split('/douyin-covers/',1)[-1] + on_local=False + try: + urllib.request.urlopen('http://127.0.0.1:8333/douyin-covers/'+key, timeout=2).read(8) + on_local=True + except Exception: + pass + if on_local: + new='https://s3.nomadro.com/douyin-covers/'+key + to_s3+=1 + else: + # prefer dy.nomadro.live public path (peer VPS bucket) + new='https://dy.nomadro.live/douyin-covers/'+key + to_live+=1 + if new!=u: + conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid)) +conn.commit() +print('point_s3', to_s3, 'point_dy_live', to_live) +from collections import Counter +c=Counter() +for (u,) in conn.execute("SELECT CASE WHEN avatar_url LIKE 'https://dy.nomadro.live%' THEN 'dy.live' WHEN avatar_url LIKE 'https://s3.nomadro.com%' THEN 's3' WHEN avatar_url LIKE 'https://dy.nomadro.com%' THEN 'dy.com' ELSE 'other' END FROM rooms WHERE avatar_url LIKE 'http%'"): + c[u]+=1 +print(dict(c)) +PY +# also pool urls +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + try: + n=0 + for a,b in [ + ('https://dy.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers'), + ('https://s3.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers'), + ]: + # only rewrite s3->live for keys missing locally — skip bulk for pool; just dy.com -> live + pass + cur=conn.execute("UPDATE yt_assign_pool_urls SET cover_url=REPLACE(cover_url,'https://dy.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers') WHERE cover_url LIKE 'https://dy.nomadro.com/douyin-covers%'") + print('pool_dycom', cur.rowcount) + conn.commit() + except Exception as e: + print('pool', e) +PY +"""), flush=True) +c.close() + +# public verify avatars now +print("=== verify ===", flush=True) +for u in [ + "https://dy.nomadro.live/douyin-covers/covers/avatars/16693589495.jpg", + "https://dy.nomadro.live/douyin-covers/covers/avatars/288944177940.jpg", + "https://dy.nomadro.live/douyin-covers/covers/avatars/562629369787.jpg", + "https://s3.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg", + "https://dy.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg", + "https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg", +]: + try: + r=urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent":"v"}), timeout=15, context=CTX) + print(r.status, u) + except urllib.error.HTTPError as e: + print("HTTP", e.code, u) + except Exception as ex: + print("ERR", ex, u) + +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dual_vps_s3_images4.py b/scripts/_fix_dual_vps_s3_images4.py new file mode 100644 index 0000000..5bc970c --- /dev/null +++ b/scripts/_fix_dual_vps_s3_images4.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Write clean nginx conf (one /douyin-covers); probe avatars correctly; deploy FE api.js.""" +from __future__ import annotations + +import ssl +import sys +import time +import urllib.error +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805" + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, script, timeout=300): + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put(c, data: bytes, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(data) + sftp.close() + + +NGINX = r''' +server { + server_name dy.nomadro.live; + client_max_body_size 200m; + + location ^~ /douyin-covers/ { + proxy_http_version 1.1; + proxy_pass http://127.0.0.1:8333; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + } + + location ^~ /api/ { + proxy_pass http://127.0.0.1:8014; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + } + # files only — do not proxy the /covers page (Next) + location ^~ /covers/ { + proxy_pass http://127.0.0.1:8014; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + } + location ^~ /_/ { + proxy_pass http://127.0.0.1:8092; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + } + include /etc/nginx/conf.d/douyinweb-neko-locations.inc; + + location / { + proxy_pass http://127.0.0.1:4015; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 60s; + } + + listen 443 ssl; # managed by Certbot + ssl_certificate /etc/letsencrypt/live/dy.nomadro.live/fullchain.pem; # managed by Certbot + ssl_certificate_key /etc/letsencrypt/live/dy.nomadro.live/privkey.pem; # managed by Certbot + include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot +} +server { + if ($host = dy.nomadro.live) { + return 301 https://$host$request_uri; + } # managed by Certbot + + listen 80; + server_name dy.nomadro.live; + return 404; # managed by Certbot +} +''' + +print("=== write clean nginx ===", flush=True) +c = connect(DY) +put(c, NGINX.lstrip("\n").encode(), "/etc/nginx/conf.d/dy-nomadro-live.conf") +print(run(c, r""" +set -e +cp -a /etc/nginx/conf.d/dy-nomadro-live.conf /etc/nginx/conf.d/dy-nomadro-live.conf.bak.cleanwrite.$(date +%Y%m%d%H%M%S) +nginx -t +systemctl reload nginx +echo nginx_ok +grep -n douyin-covers /etc/nginx/conf.d/dy-nomadro-live.conf +"""), flush=True) + +# Correct avatar existence probe + rewrite +print(run(c, r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request, urllib.error +from collections import Counter + +def exists(url: str) -> bool: + try: + urllib.request.urlopen(url, timeout=3).read(8) + return True + except Exception: + return False + +with _lock: + conn=_connect() + rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'http%'").fetchall() + c=Counter(); on_dy=on_s3=0 + for rid,u in rows: + u=str(u or '') + if '/douyin-covers/' not in u: + continue + key=u.split('/douyin-covers/',1)[-1] + local=exists('http://127.0.0.1:8333/douyin-covers/'+key) + if local: + on_dy+=1 + new='https://dy.nomadro.live/douyin-covers/'+key + else: + # keep s3 host — may exist on dylive bucket + new='https://s3.nomadro.com/douyin-covers/'+key + if exists(new): + on_s3+=1 + if new!=u: + conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid)) + host='dy.live' if new.startswith('https://dy.nomadro.live') else ('s3' if new.startswith('https://s3.nomadro.com') else 'other') + c[host]+=1 + conn.commit() + print('on_dy_bucket', on_dy, 'confirmed_on_s3_public', on_s3) + print('hosts', dict(c)) + # smoke a few + for (u,) in conn.execute("SELECT avatar_url FROM rooms WHERE avatar_url LIKE 'http%' LIMIT 8"): + print('sample', u, 'ok' if exists(u) else 'MISS') +PY +"""), flush=True) +c.close() + +# dylive: rewrite avatars based on local existence vs dy.live +print("=== dylive avatar rewrite ===", flush=True) +c = connect(DYLIVE) +print(run(c, r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +import urllib.request +from collections import Counter + +def exists(url: str) -> bool: + try: + urllib.request.urlopen(url, timeout=4).read(8) + return True + except Exception: + return False + +with _lock: + conn=_connect() + rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'http%'").fetchall() + c=Counter() + for rid,u in rows: + u=str(u or '') + if '/douyin-covers/' not in u: + continue + key=u.split('/douyin-covers/',1)[-1] + if exists('http://127.0.0.1:8333/douyin-covers/'+key): + new='https://s3.nomadro.com/douyin-covers/'+key + elif exists('https://dy.nomadro.live/douyin-covers/'+key): + new='https://dy.nomadro.live/douyin-covers/'+key + else: + new='https://s3.nomadro.com/douyin-covers/'+key # leave; cover API still works + if new!=u: + conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid)) + c['s3' if 's3.nomadro.com' in new else ('live' if 'dy.nomadro.live' in new else 'other')]+=1 + conn.commit() + print('hosts', dict(c)) + ok=miss=0 + for (u,) in conn.execute("SELECT avatar_url FROM rooms WHERE avatar_url LIKE 'http%' LIMIT 15"): + e=exists(u) + ok+=e; miss+= (not e) + print('sample', 'OK' if e else 'MISS', u[-70:]) + print('probe_ok', ok, 'miss', miss) +PY +"""), flush=True) +c.close() + +# Deploy api.js + rebuild frontend on both (or at least copy into .next if standalone hard) +api_js = open(r"c:\Users\admin\Desktop\douyinWEB\frontend\src\lib\api.js", "rb").read() +for label, host in [("dy", DY), ("dylive", DYLIVE)]: + print(f"=== deploy api.js + rebuild FE {label} ===", flush=True) + c = connect(host) + put(c, api_js, "/opt/douyinWEB/frontend/src/lib/api.js") + print( + run( + c, + r""" +set -e +cd /opt/douyinWEB/frontend +# quick rebuild — may take a few minutes +if [ -f package.json ]; then + export NODE_OPTIONS=--max-old-space-size=3072 + npm run build 2>&1 | tail -40 + systemctl restart douyinweb-web + sleep 2 + systemctl is-active douyinweb-web +fi +""", + timeout=600, + ), + flush=True, + ) + c.close() + +print("=== final public verify ===", flush=True) +urls = [ + "https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg", + "https://dy.nomadro.live/douyin-covers/covers/avatars/16693589495.jpg", + "https://s3.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg", + "https://dy.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg", + "https://dylive.nomadro.com/api/sessions/b9197cd9-b9af-432f-8e2a-880370ce75da/cover", + "https://dy.nomadro.live/api/sessions/ab13d4f5-9639-40db-a40f-6af8443f3757/cover", +] +for u in urls: + try: + r = urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "v"}), timeout=20, context=CTX) + print(r.status, r.headers.get("content-type"), u) + except urllib.error.HTTPError as e: + print("HTTP", e.code, u) + except Exception as ex: + print("ERR", ex, u) +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dy_api_bind_like_dylive.py b/scripts/_fix_dy_api_bind_like_dylive.py new file mode 100644 index 0000000..8e85c35 --- /dev/null +++ b/scripts/_fix_dy_api_bind_like_dylive.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Align dy douyinweb-api bind with dylive (0.0.0.0:8014). Do not touch dylive.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "108.174.50.68" +PASS = "Xiao4669805" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as e: + print(e, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + cmd = r""" +set -e +UNIT=/etc/systemd/system/douyinweb-api.service +cp -a "$UNIT" "${UNIT}.bak_bind_$(date +%Y%m%d%H%M%S)" +echo '--- before ---' +grep ExecStart "$UNIT" +# only change host bind; keep everything else +sed -i 's|--host 127\.0\.0\.1 --port 8014|--host 0.0.0.0 --port 8014|g' "$UNIT" +echo '--- after ---' +grep ExecStart "$UNIT" +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 3 +echo api=$(systemctl is-active douyinweb-api) +ss -lntp | grep 8014 || true +NAME=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | head -1) +echo CONTAINER=$NAME +echo -n 'host.docker.internal -> ' +docker exec "$NAME" curl -sS -m 4 -o /dev/null -w '%{http_code}' http://host.docker.internal:8014/api/health || echo fail +echo +echo -n '172.17.0.1 -> ' +docker exec "$NAME" curl -sS -m 4 -o /dev/null -w '%{http_code}' http://172.17.0.1:8014/api/health || echo fail +echo +echo -n 'gateway via host-gateway IP -> ' +GW=$(docker inspect "$NAME" --format '{{range .NetworkSettings.Networks}}{{.Gateway}}{{end}}') +echo -n "GW=$GW " +docker exec "$NAME" curl -sS -m 4 -o /dev/null -w '%{http_code}' "http://${GW}:8014/api/health" || echo fail +echo +# force one CDP + wait a bit for extension if Live page open +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import youtube_neko, yt_assign_db +print('poll_ids', youtube_neko._neko_ids_for_cdp_poll()) +print('poll', json.dumps(youtube_neko.poll_studio_cdp_once(), ensure_ascii=False)[:500]) +time.sleep(8) +# check recent ingest via journal is done outside +for g in yt_assign_db.list_groups(include_urls=False): + if int(g.get('neko_instance_id') or 0)==6: + snap=youtube_neko.studio_snapshot_for_group(g, max_age_sec=120) + print('SNAP', g.get('name'), {k:snap.get(k) for k in ('live_page_open','on_air','viewer_count','total_views','detect_source','url')}) +PY +journalctl -u douyinweb-api --since '2 min ago' --no-pager | grep -c 'live/ingest' || true +journalctl -u douyinweb-api --since '2 min ago' --no-pager | grep 'live/ingest' | tail -5 +""" + _i, o, e = c.exec_command(cmd, timeout=120, get_pty=True) + chan = o.channel + t0 = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - t0 > 110: + print("TIMEOUT", flush=True) + break + time.sleep(0.12) + print("\n[exit", chan.recv_exit_status(), "]", flush=True) + c.close() + print("DY_BIND_ALIGNED", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_dy_api_hang_and_softreload_off.py b/scripts/_fix_dy_api_hang_and_softreload_off.py new file mode 100644 index 0000000..d19bd25 --- /dev/null +++ b/scripts/_fix_dy_api_hang_and_softreload_off.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Revive hung dy API; stop extra Neko; sync soft-reload-off launch script. No recreate.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +RAW = (ROOT / "backend/neko/browser-launch.sh").read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=180) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +# --- dy revive --- +print("=== dy revive ===", flush=True) +dy = connect("108.174.50.68") +sftp = dy.open_sftp() +with sftp.file("/tmp/browser-launch-noreload.sh", "wb") as f: + f.write(RAW) +sftp.chmod("/tmp/browser-launch-noreload.sh", 0o755) +sftp.close() + +_i, o, e = dy.exec_command( + r""" +set +e +echo 'BEFORE api stat:' +ps -o pid,stat,etime,%cpu,%mem,cmd -p $(pgrep -f 'uvicorn app.main' | head -1) 2>/dev/null + +# stop non-enabled nekos (keep profile; only stop containers) +cd /opt/douyinWEB/backend +KEEP=$(./.venv/bin/python - <<'PY' +from app import yt_assign_db +ids=set() +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if g.get('neko_enabled') and int(g.get('neko_instance_id') or 0)>0: + ids.add(int(g['neko_instance_id'])) +print(' '.join(str(i) for i in sorted(ids)) or '') +PY +) +echo KEEP_NEKO=$KEEP +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + id=${n##*-} + keep=0 + for k in $KEEP; do [ "$id" = "$k" ] && keep=1; done + if [ "$keep" = "1" ]; then echo keep $n; else echo stop $n; docker stop "$n"; fi +done + +# revive hung API (D-state) +systemctl restart douyinweb-api +sleep 5 +systemctl is-active douyinweb-api +for i in 1 2 3 4 5; do + code=$(curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo 000) + echo try_$i=$code + [ "$code" = "200" ] && break + sleep 2 +done + +# sync launch script (soft-reload off by default) — write host file only; remount on next neko restart +cat /tmp/browser-launch-noreload.sh > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh +grep -n 'NEKO_STUDIO_SOFT_RELOAD' /opt/douyinWEB/backend/neko/browser-launch.sh | head -3 + +# remount keep neko browser-launch without long downtime: docker restart keep only +for k in $KEEP; do + name=douyinweb-neko-$k + docker ps --format '{{.Names}}' | grep -qx "$name" || docker start "$name" + docker restart "$name" +done +sleep 12 +for k in $KEEP; do + docker exec douyinweb-neko-$k supervisorctl status google-chrome 2>/dev/null + docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}' douyinweb-neko-$k +done + +curl -sS -m 8 -o /dev/null -w 'health:%{http_code} t=%{time_total}\n' http://127.0.0.1:8014/api/health +curl -sS -m 8 -o /dev/null -w 'home:%{http_code} t=%{time_total}\n' http://127.0.0.1:4015/ +free -m | head -2 +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +echo DY_OK +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +dy.close() + +# --- dylive: sync soft-reload-off only (don't restart unless needed) --- +print("=== dylive sync launch ===", flush=True) +dl = connect("107.173.30.245") +sftp = dl.open_sftp() +with sftp.file("/tmp/browser-launch-noreload.sh", "wb") as f: + f.write(RAW) +sftp.chmod("/tmp/browser-launch-noreload.sh", 0o755) +sftp.close() +_i, o, e = dl.exec_command( + r""" +set +e +cat /tmp/browser-launch-noreload.sh > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh +# remount running nekos so GC loop picks up soft-reload-off +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + docker restart "$n" +done +sleep 12 +curl -sS -m 8 -o /dev/null -w 'health:%{http_code}\n' http://127.0.0.1:8014/api/health +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + docker exec "$n" grep -n 'NEKO_STUDIO_SOFT_RELOAD' /etc/neko/browser-launch.sh | head -2 + docker exec "$n" supervisorctl status google-chrome 2>/dev/null | head -1 +done +free -m | head -2 +echo DYLIVE_OK +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +dl.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dy_covers_opsneko_frp.py b/scripts/_fix_dy_covers_opsneko_frp.py new file mode 100644 index 0000000..cfb995b --- /dev/null +++ b/scripts/_fix_dy_covers_opsneko_frp.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Fix dy.nomadro.com: FRP-aux S3 + ops-neko tunnels; Caddy covers + /ops-neko/*.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST, PORT, USER, PW = "107.173.30.245", 22, "root", "Xiao4669805" +CADDY = "/etc/caddy/sites/dy.nomadro.com.caddy" +UNIT = "/etc/systemd/system/dy-frp-http-aux.service" +TS = time.strftime("%Y%m%d_%H%M%S") + + +def run(c, cmd, t=120): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-12000:] if len(out) > 12000 else out, flush=True) + print(f"→ {code}", flush=True) + return code, out + + +NEW_UNIT = r"""[Unit] +Description=dy.nomadro.com FRP-aux tunnels (HTTP+ShellCrash+Neko+S3+ops-neko via :4014) +After=network-online.target frpp.service +Wants=network-online.target + +[Service] +Type=simple +Restart=always +RestartSec=3 +Environment=SSHPASS=4669805 +ExecStart=/usr/bin/sshpass -e ssh -N -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes \ + -L 127.0.0.1:18014:127.0.0.1:8014 \ + -L 127.0.0.1:14015:127.0.0.1:4015 \ + -L 127.0.0.1:9999:127.0.0.1:9999 \ + -L 127.0.0.1:9200:127.0.0.1:9200 \ + -L 127.0.0.1:9201:127.0.0.1:9201 \ + -L 127.0.0.1:9202:127.0.0.1:9202 \ + -L 127.0.0.1:9203:127.0.0.1:9203 \ + -L 127.0.0.1:9204:127.0.0.1:9204 \ + -L 127.0.0.1:9205:127.0.0.1:9205 \ + -L 127.0.0.1:9206:127.0.0.1:9206 \ + -L 127.0.0.1:9207:127.0.0.1:9207 \ + -L 127.0.0.1:18200:127.0.0.1:18200 \ + -L 127.0.0.1:18201:127.0.0.1:18201 \ + -L 127.0.0.1:18202:127.0.0.1:18202 \ + -L 127.0.0.1:18203:127.0.0.1:18203 \ + -L 127.0.0.1:18204:127.0.0.1:18204 \ + -L 127.0.0.1:18205:127.0.0.1:18205 \ + -L 127.0.0.1:18206:127.0.0.1:18206 \ + -L 127.0.0.1:18207:127.0.0.1:18207 \ + -L 127.0.0.1:28333:127.0.0.1:8333 \ + -p 4014 eric@127.0.0.1 + +[Install] +WantedBy=multi-user.target +""" + +# Python patch for caddy on remote +PATCH_PY = r''' +from pathlib import Path +import re +p = Path("/etc/caddy/sites/dy.nomadro.com.caddy") +text = p.read_text(encoding="utf-8") +bak = Path(f"/etc/caddy/sites/dy.nomadro.com.caddy.bak.{ts}") +bak.write_text(text, encoding="utf-8") +print("backup", bak) + +# 1) douyin-covers → FRP-aux local seaweed +old = """\thandle /douyin-covers/* { +\t\treverse_proxy 10.8.0.2:8333 { +\t\t\theader_up Host {host} +\t\t} +\t}""" +new = """\thandle /douyin-covers/* { +\t\treverse_proxy 127.0.0.1:28333 { +\t\t\theader_up Host {host} +\t\t} +\t}""" +if "127.0.0.1:28333" not in text: + if old not in text: + # tolerant replace + text2, n = re.subn( + r"handle /douyin-covers/\* \{\s*reverse_proxy 10\.8\.0\.2:8333 \{", + "handle /douyin-covers/* {\n\t\treverse_proxy 127.0.0.1:28333 {", + text, + count=1, + ) + if n != 1: + raise SystemExit("douyin-covers block not found") + text = text2 + else: + text = text.replace(old, new, 1) + print("patched douyin-covers -> 127.0.0.1:28333") +else: + print("douyin-covers already local 28333") + +# 2) insert ops-neko routes before douyin-covers if missing +OPS = """ +\t# Ops-Neko tab fleet (douyinweb-ops-neko-*) via FRP-aux :1820x — independent of /neko/* +\t@opsneko_noslash path_regexp opsneko_id ^/ops-neko/([0-9]+)$ +\tredir @opsneko_noslash /ops-neko/{re.opsneko_id.1}/ 308 +""" +for i in range(1, 9): + port = 18199 + i # 18200..18207 + OPS += f"""\thandle_path /ops-neko/{i}/* {{ +\t\treverse_proxy 127.0.0.1:{port} {{ +\t\t\theader_up Host {{host}} +\t\t\theader_up X-Forwarded-Proto {{scheme}} +\t\t\theader_up X-Forwarded-Host {{host}} +\t\t}} +\t}} +""" + +if "handle_path /ops-neko/1/*" not in text: + needle = "\thandle /douyin-covers/* {" + if needle not in text: + raise SystemExit("cannot find insertion point before douyin-covers") + text = text.replace(needle, OPS + "\n" + needle, 1) + print("inserted ops-neko 1..8 routes") +else: + print("ops-neko routes already present") + +p.write_text(text, encoding="utf-8") +print("wrote", p) +''' + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, PORT, USER, PW, timeout=60, banner_timeout=90, allow_agent=False, look_for_keys=False) + try: + # backup + write unit + run(c, f"cp -a {UNIT} {UNIT}.bak.{TS}") + sftp = c.open_sftp() + with sftp.open(UNIT, "w") as f: + f.write(NEW_UNIT) + with sftp.open(f"/tmp/patch_dy_caddy_{TS}.py", "w") as f: + f.write(PATCH_PY.replace("{ts}", TS)) + sftp.close() + + run(c, "systemctl daemon-reload; systemctl restart dy-frp-http-aux; sleep 3; systemctl is-active dy-frp-http-aux") + run(c, "ss -lntp | grep -E '28333|18200|18014|9200' || true") + run(c, f"python3 /tmp/patch_dy_caddy_{TS}.py") + code, out = run(c, "caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20") + if code != 0 and "Valid configuration" not in out: + print("Caddy validate failed — restoring caddy from bak") + run(c, f"cp -a /etc/caddy/sites/dy.nomadro.com.caddy.bak.{TS} {CADDY}") + return 1 + run(c, "systemctl reload caddy; sleep 2; systemctl is-active caddy") + run( + c, + r""" +set +e +curl -sS -m 12 -o /dev/null -w 'covers=%{http_code}\n' https://dy.nomadro.com/douyin-covers/ +curl -sS -m 12 -o /dev/null -w 'opsneko1_noslash=%{http_code}\n' https://dy.nomadro.com/ops-neko/1 +curl -sS -m 12 -o /dev/null -w 'opsneko1_slash=%{http_code}\n' https://dy.nomadro.com/ops-neko/1/ +curl -sS -m 8 -o /dev/null -w 'local_28333=%{http_code}\n' http://127.0.0.1:28333/ +curl -sS -m 8 -o /dev/null -w 'local_18200=%{http_code}\n' http://127.0.0.1:18200/ +# sniff ops-neko is not Next login +curl -sS -m 10 -D- -o /tmp/ops1.html https://dy.nomadro.com/ops-neko/1/ | head -20 +head -c 200 /tmp/ops1.html; echo +curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\n' https://dylive.nomadro.com/api/health +curl -sS -m 12 -o /dev/null -w 'dy_api=%{http_code}\n' https://dy.nomadro.com/api/health +""", + ) + return 0 + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_fix_dy_dylive_now.py b/scripts/_fix_dy_dylive_now.py new file mode 100644 index 0000000..825a57a --- /dev/null +++ b/scripts/_fix_dy_dylive_now.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Fix dy.nomadro.com 502 + dylive.nomadro.com invalid response.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS_HOST = "107.173.30.245" +VPS_PASS = "Xiao4669805" +GUEST_PASS = "4669805" + + +def ssh(host, port, user, pw, tries=12): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + pw, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print(f"ssh {host}:{port} ok try={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"ssh {host}:{port} retry {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(4) + raise RuntimeError(f"ssh fail {host}:{port}: {last}") + + +def run(c, cmd, t=120, label=""): + print(f"\n[{label}]$ {cmd[:250]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-7000:] if len(out) > 7000 else out, flush=True) + print(f"[{label}]→{code}", flush=True) + return code, out + + +def probe(): + print("\n=== PUBLIC PROBE ===", flush=True) + with httpx.Client(follow_redirects=False, timeout=25) as cl: + for url in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/youtube", + "https://dylive.nomadro.com/", + ]: + try: + r = cl.get(url) + print( + f"{url} -> {r.status_code} ctype={r.headers.get('content-type','')[:40]} " + f"loc={r.headers.get('location','')[:50]} body={r.text[:80]!r}", + flush=True, + ) + except Exception as ex: + print(f"{url} ERR {ex}", flush=True) + + +def main() -> int: + probe() + + v = ssh(VPS_HOST, 22, "root", VPS_PASS) + try: + # --- dylive local stack --- + run( + v, + "uptime; free -h | head -2; " + "systemctl restart caddy; " + "systemctl restart douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web; " + "sleep 4; " + "systemctl is-active caddy douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb nginx; " + "curl -sS -m 12 http://127.0.0.1:8014/api/health | head -c 250; echo; " + "curl -sS -m 12 -o /dev/null -w 'local_web=%{http_code}\\n' http://127.0.0.1:4015/; " + "curl -sS -m 12 -o /dev/null -w 'local_yt=%{http_code}\\n' http://127.0.0.1:4015/youtube", + t=90, + label="dylive-restart", + ) + + # --- WG for dy.nomadro.com --- + run( + v, + "systemctl start frpp nginx 'wg-quick@wg-dy' 2>/dev/null; " + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -20; " + "ping -c 3 -W 2 10.8.0.2 | tail -5 || true", + t=60, + label="wg-bounce-vps", + ) + finally: + v.close() + + # Physical guest via FRP + try: + g = ssh(VPS_HOST, 4014, "eric", GUEST_PASS) + try: + run( + g, + f"echo '{GUEST_PASS}' | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -15; " + "ping -c 3 -W 2 10.8.0.1 | tail -4; " + "systemctl restart douyinweb-api douyinweb-web 2>/dev/null || true; " + "sleep 3; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 200; echo; " + "curl -sS -m 10 -o /dev/null -w local_web=%{http_code}\\\\n http://127.0.0.1:4015/" + "'", + t=120, + label="guest-fix", + ) + finally: + g.close() + except Exception as ex: + print(f"guest FRP failed: {ex}", flush=True) + + # Re-check tunnel from VPS + v = ssh(VPS_HOST, 22, "root", VPS_PASS) + try: + run( + v, + "wg show wg-dy | head -18; " + "ping -c 4 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 12 -o /dev/null -w 'via_wg_api=%{http_code}\\n' http://10.8.0.2:8014/api/health; " + "curl -sS -m 12 -o /dev/null -w 'via_wg_web=%{http_code}\\n' http://10.8.0.2:4015/; " + "systemctl reload caddy 2>/dev/null || systemctl restart caddy; " + "sleep 1; " + "curl -sS -m 15 -o /dev/null -w 'caddy_dy=%{http_code}\\n' -H 'Host: dy.nomadro.com' https://127.0.0.1/api/health -k; " + "curl -sS -m 15 -o /dev/null -w 'caddy_dylive=%{http_code}\\n' -H 'Host: dylive.nomadro.com' https://127.0.0.1/api/health -k", + t=90, + label="final-tunnel", + ) + finally: + v.close() + + time.sleep(2) + probe() + print("\nDONE fix", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_fix_dy_nat_restart_chrome.py b/scripts/_fix_dy_nat_restart_chrome.py new file mode 100644 index 0000000..2a2ff3c --- /dev/null +++ b/scripts/_fix_dy_nat_restart_chrome.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Fix dy NAT1TO1 regression + restart chrome on running nekos with new flags + verify health.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) + + +def run(cmd: str, t: int = 240) -> str: + print("\n=====", cmd[:90].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return out + + +run( + r""" +set -euo pipefail +# force public NAT, never 198.18 +grep -q '^DY_NEKO_NAT1TO1=' /etc/douyinweb.env \ + && sed -i 's/^DY_NEKO_NAT1TO1=.*/DY_NEKO_NAT1TO1=108.174.50.68/' /etc/douyinweb.env \ + || echo 'DY_NEKO_NAT1TO1=108.174.50.68' >> /etc/douyinweb.env +grep -q '^DY_NEKO_VPS_NAT1TO1=' /etc/douyinweb.env \ + && sed -i 's/^DY_NEKO_VPS_NAT1TO1=.*/DY_NEKO_VPS_NAT1TO1=108.174.50.68/' /etc/douyinweb.env \ + || echo 'DY_NEKO_VPS_NAT1TO1=108.174.50.68' >> /etc/douyinweb.env + +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_NEKO_NAT1TO1=108.174.50.68 +export DY_NEKO_VPS_NAT1TO1=108.174.50.68 +./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +from pathlib import Path +# rewrite compose with correct NAT; do not start extras +out = yn.ensure_capacity(8, start_instances=set(), reconcile_running=False) +print(out) +text = Path(yn._compose_path()).read_text(encoding='utf-8') +for ln in text.splitlines(): + if 'NAT' in ln.upper() or 'nat1' in ln.lower(): + print('compose', ln.strip()[:140]) +PY + +# restart chrome on all running nekos so new flags apply +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + echo "RESTART_CHROME $name" + docker exec "$name" supervisorctl restart google-chrome || true +done +sleep 10 +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + echo "== $name ==" + docker exec "$name" supervisorctl status google-chrome || true + docker exec "$name" sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "no-turbofan|no-wasm|Passage|renderer-process" | head -5; break ;; + esac + done' || true + # oom protect + for pid in $(docker top "$name" -eo pid 2>/dev/null | awk 'NR>1{print $1}'); do + echo -800 > /proc/$pid/oom_score_adj 2>/dev/null || true + done +done + +# reopen studio on neko-7 +docker exec douyinweb-neko-7 python3 -c ' +import json,urllib.request,time +S="https://studio.youtube.com/channel/UC6ZbNjX9jg6-AeQrqwday8Q/livestreaming" +for i in range(30): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version",timeout=2).read(); break + except Exception: + time.sleep(1) +req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") +print(urllib.request.urlopen(req,timeout=15).read()[:80]) +time.sleep(5) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print("TAB",(t.get("title") or "")[:55], "|", (t.get("url") or "")[:100]) +' + +sleep 3 +curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 300; echo +systemctl show douyinweb-api -p MemoryHigh,MemoryMax,OOMScoreAdjust +free -h | head -3 +docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' | head -10 +grep -n NAT1TO1 /etc/douyinweb.env +""" +) +c.close() +print("DONE") diff --git a/scripts/_fix_dy_neko10_sigill_timeslot.py b/scripts/_fix_dy_neko10_sigill_timeslot.py new file mode 100644 index 0000000..c675974 --- /dev/null +++ b/scripts/_fix_dy_neko10_sigill_timeslot.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Fix dy neko-10 SIGILL (jitless) + timeslot context. Never recreate container.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=240): + print("\n=====", cmd[:90].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return out + + +text = LOCAL.read_text(encoding="utf-8") +assert "--jitless" in text + +c = connect() +sftp = c.open_sftp() +tmp = "/tmp/browser-launch-jitless-n10.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) +sftp.close() + +run( + c, + rf""" +set +e +export DY_NEKO_NAT1TO1=108.174.50.68 +echo '=== mem/neko ===' +free -h | head -2 +docker ps -a --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort +echo '=== timeslot / assign neko10 ===' +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env 2>/dev/null || true; set +a +./.venv/bin/python - <<'PY' +from app import db, yt_assign_db +sm = db.get_settings_map() +print('time_slot_mode', sm.get('youtube_relay_time_slot_mode')) +print('timeslot_test', sm.get('youtube_relay_timeslot_test'), sm.get('youtube_relay_timeslot_test_group_id')) +print('relay_enabled', sm.get('youtube_relay_enabled')) +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if int(g.get('neko_instance_id') or 0) == 10 or 'neko' in str(g.get('name') or '').lower(): + print('g', g.get('name'), 'neko', g.get('neko_instance_id'), 'cat', g.get('category'), + 'armed', g.get('time_slot_armed'), 'neko_en', g.get('neko_enabled'), + 'yt', (g.get('youtube_channel_id') or '')[:24]) +# all time_slot groups +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if str(g.get('category') or '') == 'time_slot' or int(g.get('neko_instance_id') or 0) == 10: + print('slot', g.get('name'), 'id', g.get('id')[:8], 'neko', g.get('neko_instance_id'), + 'en', g.get('enabled'), 'neko_en', g.get('neko_enabled')) +PY + +# ensure neko-10 running (start only) +docker start douyinweb-neko-10 2>/dev/null || true +sleep 3 +docker ps --filter name=douyinweb-neko-10 --format '{{{{.Names}}}} {{{{.Status}}}}' + +# patch mounted inode in-place +INO=$(docker exec douyinweb-neko-10 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{{print $1}}') +MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$INO" '$1==i{{print $NF; exit}}') +echo INO=$INO MATCH=$MATCH +[ -n "$MATCH" ] && cat {tmp} > "$MATCH" +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +docker exec douyinweb-neko-10 grep -n jitless /etc/neko/browser-launch.sh || echo 'STALE_MOUNT' + +# if stale, overwrite ALL copies under neko dir (same as before) +for f in /opt/douyinWEB/backend/neko/browser-launch.sh*; do + [ -f "$f" ] || continue + cat {tmp} > "$f" || true +done +docker exec douyinweb-neko-10 grep -n jitless /etc/neko/browser-launch.sh + +docker exec douyinweb-neko-10 supervisorctl restart google-chrome +sleep 12 +docker exec douyinweb-neko-10 supervisorctl status google-chrome +docker exec douyinweb-neko-10 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "jitless|js-flags|wasm"; break;; + esac +done' + +# resolve studio URL for group on neko 10 +STUDIO=$(cd /opt/douyinWEB/backend && ./.venv/bin/python - <<'PY' +from app import yt_assign_db +url='' +ycid='' +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if int(g.get('neko_instance_id') or 0)==10: + ycid=str(g.get('youtube_channel_id') or '').strip() + name=g.get('name') + print('picked', name, ycid, file=__import__('sys').stderr) + break +if ycid: + url=f'https://studio.youtube.com/channel/{{ycid}}/livestreaming' +else: + url='https://studio.youtube.com/' +print(url) +PY +) +echo STUDIO=$STUDIO + +docker exec douyinweb-neko-10 python3 -c " +import json,urllib.request,time,os +S=os.environ.get('S') or '''$STUDIO''' +S=S.strip() +for i in range(40): + try: + urllib.request.urlopen('http://127.0.0.1:9222/json/version',timeout=2).read(); print('devtools_ok'); break + except Exception: + time.sleep(1) +else: + raise SystemExit('no_devtools') +tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read()) +for t in tabs: + if t.get('type')=='page' and t.get('id'): + try: + urllib.request.urlopen('http://127.0.0.1:9222/json/close/'+t['id'], timeout=3).read() + print('closed', (t.get('url') or '')[:80]) + except Exception as e: + print('close_err', e) +req=urllib.request.Request('http://127.0.0.1:9222/json/new?'+S, method='PUT') +print('open', urllib.request.urlopen(req,timeout=20).read()[:100]) +ok=False +for i in range(12): + time.sleep(2) + tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read()) + pages=[t for t in tabs if t.get('type')=='page'] + for t in pages: + print('t%s' % i, (t.get('title') or '')[:70], '|', (t.get('url') or '')[:110]) + titles=' '.join((t.get('title') or '') for t in pages) + urls=' '.join((t.get('url') or '') for t in pages) + bad=('Snap' in titles) or ('SIGILL' in titles) or ('chrome-error' in urls) or (\"Can't open\" in titles) + good=('studio.youtube.com' in urls) and (not bad) + if good: + print('STUDIO_OK'); ok=True; break +if not ok: + print('STUDIO_STILL_BAD') +" + +# also ensure other RUNNING nekos have jitless visible (restart chrome only if missing) +for name in $(docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}}'); do + if docker exec "$name" grep -q jitless /etc/neko/browser-launch.sh 2>/dev/null; then + echo OK_FLAGS_$name + else + echo FIX_FLAGS_$name + ino=$(docker exec "$name" sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{{print $1}}') + match=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* | awk -v i="$ino" '$1==i{{print $NF; exit}}') + [ -n "$match" ] && cat {tmp} > "$match" + docker exec "$name" supervisorctl restart google-chrome || true + fi +done + +dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -3 +curl -sk -o /dev/null -w 'neko10:%{{http_code}}\n' https://dy.nomadro.live/neko/10/ +""", +) + +c.close() +print("DONE") diff --git a/scripts/_fix_dy_neko7_sigill_hard.py b/scripts/_fix_dy_neko7_sigill_hard.py new file mode 100644 index 0000000..5222154 --- /dev/null +++ b/scripts/_fix_dy_neko7_sigill_hard.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Deep-diag dy neko-7 SIGILL; apply jitless + CPU-safe chrome flags; recover Studio.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +STUDIO = "https://studio.youtube.com/channel/UC6ZbNjX9jg6-AeQrqwday8Q/livestreaming" + + +def connect(retries=8): + last = None + for i in range(retries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + last = e + print("ssh_retry", i, e, flush=True) + time.sleep(2 + i) + raise SystemExit(last) + + +def run(c, cmd, t=300): + print("\n=====", cmd[:90].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return out + + +c = connect() + +# 1) diagnose +run( + c, + r""" +set +e +echo '=== cpu ===' +lscpu | egrep 'Model name|Flags|Architecture|Vendor' | head -15 +grep -m1 flags /proc/cpuinfo | tr ' ' '\n' | grep -E '^(avx|avx2|avx512|sse4|amx)' | sort -u +echo '=== mem ===' +free -h | head -3 +echo '=== chrome ver / recent traps ===' +docker exec douyinweb-neko-7 sh -c 'google-chrome --version 2>/dev/null; chromium --version 2>/dev/null; uname -m' +dmesg -T 2>/dev/null | grep -iE 'invalid opcode|SIGILL|oom-kill' | tail -12 +echo '=== neko7 mem / tabs ===' +docker stats douyinweb-neko-7 --no-stream --format '{{.MemUsage}}' +docker exec douyinweb-neko-7 python3 -c ' +import json,urllib.request +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) + for t in tabs: + if t.get("type")=="page": + print((t.get("title") or "")[:50], "|", (t.get("url") or "")[:100]) +except Exception as e: + print("cdp_err", e) +' +""", +) + +# 2) patch local browser-launch to use --jitless (nuclear V8) + disable more native paths +src = LOCAL.read_text(encoding="utf-8") +old = '--js-flags="--max-old-space-size=192 --no-wasm-simd --no-turbofan"' +new = '--js-flags="--max-old-space-size=192 --jitless --no-wasm-simd"' +if old in src: + src = src.replace(old, new) +elif "--jitless" not in src: + src = src.replace( + '--js-flags="--max-old-space-size=192 --no-wasm-simd --no-turbofan"', + new, + ) +# also force render_mode legacy path is env; add chrome flag to disable wasm entirely via feature +old_df = "--disable-features=IsolateOrigins,site-per-process,TranslateUI,BackForwardCache,WebAssemblySimd,WebAssemblyLazyCompilation,OptimizationGuideModelDownloading,OptimizationHints,PageContentAnnotations,PassageEmbeddings" +new_df = old_df + ",WebAssembly,CalculateNativeWinOcclusion,CanvasOopRasterization,Vulkan,UseSkiaRenderer" +if old_df in src and ",WebAssembly," not in src.split(old_df)[0] + src.split(old_df)[1][:80]: + # careful replace once + if new_df not in src: + src = src.replace(old_df, new_df, 1) + +# Add CHROME_WRAPPER-style env note: prepend OPENSSL / clear for process in launch_browser +marker = ' echo -800 > /proc/self/oom_score_adj 2>/dev/null || true' +inject = ''' # Mask AVX512-ish paths that SIGILL on some colo CPUs / Chrome builds + export OPENSSL_ia32cap="~0x200000200000000" + export CHROME_FORCE_WAKE_ON_LAN=0 + echo -800 > /proc/self/oom_score_adj 2>/dev/null || true''' +if "OPENSSL_ia32cap" not in src and marker in src: + src = src.replace(marker, inject, 1) + +LOCAL.write_text(src, encoding="utf-8") +assert "--jitless" in LOCAL.read_text(encoding="utf-8") + +# 3) deploy in-place to mounted inode + recreate neko-7 if needed +sftp = c.open_sftp() +tmp = "/tmp/browser-launch-jitless.sh" +with sftp.file(tmp, "wb") as f: + f.write(LOCAL.read_bytes()) +sftp.chmod(tmp, 0o755) +sftp.close() + +run( + c, + rf""" +set -euo pipefail +export DY_NEKO_NAT1TO1=108.174.50.68 +# overwrite ALL browser-launch inodes under neko dir +for f in /opt/douyinWEB/backend/neko/browser-launch.sh*; do + [ -f "$f" ] || continue + case "$f" in *.bak*) ;; esac + cat {tmp} > "$f" || true +done +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh + +# verify visible inside 7 +docker exec douyinweb-neko-7 grep -n 'jitless\|OPENSSL_ia32cap\|WebAssembly,' /etc/neko/browser-launch.sh || true +if ! docker exec douyinweb-neko-7 grep -q jitless /etc/neko/browser-launch.sh; then + echo FORCE_RECREATE + # recreate container to remount file + cd /opt/douyinWEB/backend + set -a; source /etc/douyinweb.env; set +a + export DY_NEKO_NAT1TO1=108.174.50.68 + ./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +import subprocess +# keep profile; recreate via docker compose labels +import json +name='douyinweb-neko-7' +insp=json.loads(subprocess.check_output(['docker','inspect',name], text=True))[0] +labels=insp.get('Config',{{}}).get('Labels') or {{}} +wd=labels.get('com.docker.compose.project.working_dir') +proj=labels.get('com.docker.compose.project') +svc=labels.get('com.docker.compose.service') +print('compose', wd, proj, svc) +if wd and svc: + subprocess.check_call(['docker','compose','-p',proj,'up','-d','--force-recreate','--no-deps',svc], cwd=wd) +else: + # fallback: stop/rm + ensure start 7 only + subprocess.call(['docker','stop',name]) + subprocess.call(['docker','rm',name]) + print(yn.ensure_capacity(8, start_instances={{7}}, reconcile_running=True)) +PY + sleep 15 +fi +docker exec douyinweb-neko-7 grep -n 'jitless\|OPENSSL' /etc/neko/browser-launch.sh +docker exec douyinweb-neko-7 supervisorctl restart google-chrome +sleep 14 +docker exec douyinweb-neko-7 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "jitless|wasm|js-flags|renderer-process|OPENSSL" ; break ;; + esac +done' +# close all pages then open ONE studio livestreaming +docker exec douyinweb-neko-7 python3 -c ' +import json,urllib.request,time +S="{STUDIO}" +for i in range(40): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version",timeout=2).read(); break + except Exception: + time.sleep(1) +else: + raise SystemExit("no_devtools") +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +for t in tabs: + if t.get("type")=="page" and t.get("id"): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/close/"+t["id"], timeout=3).read() + print("closed", (t.get("url") or "")[:80]) + except Exception as e: + print("close_err", e) +req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") +print("open", urllib.request.urlopen(req,timeout=20).read()[:100]) +# wait and check title not Aw Snap / Cant open +for i in range(12): + time.sleep(2) + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) + pages=[t for t in tabs if t.get("type")=="page"] + for t in pages: + title=(t.get("title") or "") + url=(t.get("url") or "") + print(f"t{i}", title[:70], "|", url[:100]) + bad=any("Snap" in (t.get("title") or "") or "SIGILL" in (t.get("title") or "") or "chrome-error" in (t.get("url") or "") for t in pages) + ok=any("studio.youtube.com" in (t.get("url") or "") and "livestreaming" in (t.get("url") or "") and "Snap" not in (t.get("title") or "") for t in pages) + if ok and not bad: + print("STUDIO_OK") + break +else: + print("STUDIO_STILL_BAD") +' +dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -3 +free -h | head -2 +""", +) + +c.close() +print("DONE") diff --git a/scripts/_fix_dy_neko7_sigill_hard2.py b/scripts/_fix_dy_neko7_sigill_hard2.py new file mode 100644 index 0000000..9771876 --- /dev/null +++ b/scripts/_fix_dy_neko7_sigill_hard2.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Recover dy neko-7: start, deploy jitless launch, probe Studio stability.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +STUDIO = "https://studio.youtube.com/channel/UC6ZbNjX9jg6-AeQrqwday8Q/livestreaming" + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=360): + print("\n=====", cmd[:100].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return out + + +# ensure local has jitless +text = LOCAL.read_text(encoding="utf-8") +if "--jitless" not in text: + text = text.replace( + '--js-flags="--max-old-space-size=192 --no-wasm-simd --no-turbofan"', + '--js-flags="--max-old-space-size=192 --jitless --no-wasm-simd"', + ) + text = text.replace( + '--js-flags="--max-old-space-size=192 --no-wasm-simd"', + '--js-flags="--max-old-space-size=192 --jitless --no-wasm-simd"', + ) +if "OPENSSL_ia32cap" not in text: + text = text.replace( + " echo -800 > /proc/self/oom_score_adj 2>/dev/null || true\n \"$@\" &", + ' export OPENSSL_ia32cap="~0x200000200000000"\n' + " echo -800 > /proc/self/oom_score_adj 2>/dev/null || true\n \"$@\" &\n", + 1, + ) +LOCAL.write_text(text, encoding="utf-8") +text = LOCAL.read_text(encoding="utf-8") +assert "--jitless" in text + +c = connect() +sftp = c.open_sftp() +tmp = "/tmp/browser-launch-jitless2.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) +sftp.close() + +# Remote python as separate file to avoid f-string/brace hell +remote_py = r''' +import json, urllib.request, time, subprocess, os +STUDIO = os.environ["STUDIO"] + +def cdp(path, method=None): + url = "http://127.0.0.1:9222" + path + req = urllib.request.Request(url, method=method) if method else url + with urllib.request.urlopen(req, timeout=20) as r: + return r.read() + +for i in range(50): + try: + cdp("/json/version") + print("devtools_ok") + break + except Exception: + time.sleep(1) +else: + raise SystemExit("no_devtools") + +tabs = json.loads(cdp("/json/list")) +for t in tabs: + if t.get("type") == "page" and t.get("id"): + try: + cdp("/json/close/" + t["id"]) + print("closed", (t.get("url") or "")[:80]) + except Exception as e: + print("close_err", e) + +print("open", cdp("/json/new?" + STUDIO, method="PUT")[:120]) + +ok = False +for i in range(15): + time.sleep(2) + tabs = json.loads(cdp("/json/list")) + pages = [t for t in tabs if t.get("type") == "page"] + for t in pages: + print("t%s" % i, (t.get("title") or "")[:70], "|", (t.get("url") or "")[:110]) + titles = " ".join((t.get("title") or "") for t in pages) + urls = " ".join((t.get("url") or "") for t in pages) + bad = ("Snap" in titles) or ("SIGILL" in titles) or ("chrome-error" in urls) or ("Can't open" in titles) or ("Cant open" in titles) + good = ("studio.youtube.com" in urls) and ("livestreaming" in urls) and (not bad) + if good: + print("STUDIO_OK") + ok = True + break +if not ok: + print("STUDIO_STILL_BAD") +''' + +sftp = c.open_sftp() +with sftp.file("/tmp/neko7_cdp_probe.py", "w") as f: + f.write(remote_py) +sftp.close() + +run( + c, + rf""" +set -euo pipefail +export DY_NEKO_NAT1TO1=108.174.50.68 +export DY_NEKO_VPS_NAT1TO1=108.174.50.68 + +# sync launch script to all copies +for f in /opt/douyinWEB/backend/neko/browser-launch.sh /opt/douyinWEB/backend/neko/browser-launch.sh.bak-sigill*; do + [ -e "$f" ] || continue + cat {tmp} > "$f" 2>/dev/null || true +done +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +grep -n jitless /opt/douyinWEB/backend/neko/browser-launch.sh | head + +# start or recreate neko-7 +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_NEKO_NAT1TO1=108.174.50.68 +docker start douyinweb-neko-7 2>/dev/null || true +sleep 2 +if ! docker ps --format '{{{{.Names}}}}' | grep -qx douyinweb-neko-7; then + echo NEED_ENSURE + ./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +print(yn.ensure_capacity(8, start_instances={{7}}, reconcile_running=True)) +print('nat', yn._detect_public_ip() if hasattr(yn,'_detect_public_ip') else None) +PY +fi +docker ps -a --filter name=douyinweb-neko-7 --format '{{{{.Names}}}} {{{{.Status}}}}' +sleep 5 + +# overwrite mounted inode +INO=$(docker exec douyinweb-neko-7 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{{print $1}}') +MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* | awk -v i="$INO" '$1==i{{print $NF; exit}}') +echo INO=$INO MATCH=$MATCH +[ -n "$MATCH" ] && cat {tmp} > "$MATCH" +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +docker exec douyinweb-neko-7 grep -n jitless /etc/neko/browser-launch.sh + +# if still no jitless -> force recreate +if ! docker exec douyinweb-neko-7 grep -q jitless /etc/neko/browser-launch.sh; then + WD=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.project.working_dir"}}}}') + PROJ=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.project"}}}}') + SVC=$(docker inspect douyinweb-neko-7 --format '{{{{index .Config.Labels "com.docker.compose.service"}}}}') + echo RECREATE $WD $PROJ $SVC + cd "$WD" + docker compose -p "$PROJ" up -d --force-recreate --no-deps "$SVC" + sleep 12 + docker exec douyinweb-neko-7 grep -n jitless /etc/neko/browser-launch.sh +fi + +docker exec douyinweb-neko-7 sh -c 'google-chrome --version || true' +docker exec douyinweb-neko-7 supervisorctl restart google-chrome +sleep 12 +docker exec douyinweb-neko-7 supervisorctl status google-chrome +docker exec douyinweb-neko-7 sh -c 'for p in /proc/[0-9]*; do cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null); case "$cmd" in *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "jitless|js-flags|wasm"; break;; esac; done' + +# probe studio +docker cp /tmp/neko7_cdp_probe.py douyinweb-neko-7:/tmp/neko7_cdp_probe.py +docker exec -e STUDIO='{STUDIO}' douyinweb-neko-7 python3 /tmp/neko7_cdp_probe.py + +echo '=== traps after ===' +dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -5 +docker stats douyinweb-neko-7 --no-stream --format 'mem {{{{.MemUsage}}}}' +curl -sk -o /dev/null -w 'pub:%{{http_code}}\n' https://dy.nomadro.live/neko/7/ +""", +) + +c.close() +print("DONE") diff --git a/scripts/_fix_dy_neko_nat.py b/scripts/_fix_dy_neko_nat.py new file mode 100644 index 0000000..70e4539 --- /dev/null +++ b/scripts/_fix_dy_neko_nat.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Force Neko NAT1TO1 to public IP 108.174.50.68 on dy.nomadro.live.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +cmd = r""" +set -euo pipefail +# Persist correct public IP (avoid fake-ip 198.18.x from sing-box) +grep -q '^DY_NEKO_NAT1TO1=' /etc/douyinweb.env \ + && sed -i 's/^DY_NEKO_NAT1TO1=.*/DY_NEKO_NAT1TO1=108.174.50.68/' /etc/douyinweb.env \ + || echo 'DY_NEKO_NAT1TO1=108.174.50.68' >> /etc/douyinweb.env +# Also bake into API unit Environment if present +if grep -q 'DY_NEKO_NAT1TO1=' /etc/systemd/system/douyinweb-api.service; then + sed -i 's/Environment=DY_NEKO_NAT1TO1=.*/Environment=DY_NEKO_NAT1TO1=108.174.50.68/' /etc/systemd/system/douyinweb-api.service +else + # insert after EnvironmentFile if missing + sed -i '/EnvironmentFile=-\/etc\/douyinweb.env/a Environment=DY_NEKO_NAT1TO1=108.174.50.68' /etc/systemd/system/douyinweb-api.service || true +fi +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 3 + +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_NEKO_NAT1TO1=108.174.50.68 +./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +from app import config +print('settings_nat', getattr(config.settings, 'neko_nat1to1', None)) +print('detect', yn._detect_public_ip()) +# recreate compose with correct NAT (containers Created only — no start) +out = yn.ensure_capacity(4, start_instances=set(), reconcile_running=False) +print(out) +# show compose nat line +from pathlib import Path +text = (yn._compose_path()).read_text(encoding='utf-8') +for ln in text.splitlines(): + if 'NAT' in ln.upper() or 'nat1' in ln.lower() or 'NEKO_WEBRTC' in ln: + print('compose', ln.strip()[:120]) +PY +""" +_i, o, e = c.exec_command(cmd, timeout=180) +print((o.read() + e.read()).decode("utf-8", "replace")) +print("exit", o.channel.recv_exit_status()) +c.close() diff --git a/scripts/_fix_dy_stop_orphan_neko10.py b/scripts/_fix_dy_stop_orphan_neko10.py new file mode 100644 index 0000000..e4c38a9 --- /dev/null +++ b/scripts/_fix_dy_stop_orphan_neko10.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Stop orphan neko-10 on dy.live (DB neko_enabled=0). Do not touch FFmpeg.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + break + except Exception as e: + print("retry", e, flush=True) + time.sleep(2) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set -e +cd /opt/douyinWEB/backend +EN=$(./.venv/bin/python - <<'PY' +from app.db import _connect, _lock +with _lock: + conn=_connect() + r=conn.execute("SELECT neko_enabled FROM yt_assign_groups WHERE neko_instance_id=10 LIMIT 1").fetchone() + print(int(r[0]) if r else -1) +PY +) +echo neko10_enabled=$EN +if [ "$EN" = "0" ]; then + docker stop douyinweb-neko-10 || true + docker update --restart=no douyinweb-neko-10 2>/dev/null || true + echo stopped_orphan_neko10 +else + echo skip_enabled_$EN +fi +sleep 2 +docker ps --filter name=neko --format '{{.Names}} {{.Status}}' +uptime +mpstat 1 2 2>/dev/null | tail -4 +ps aux --sort=-%cpu | head -8 +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) +c.close() +print("ALL_DONE", flush=True) diff --git a/scripts/_fix_dylive_browser_launch_lf.py b/scripts/_fix_dylive_browser_launch_lf.py new file mode 100644 index 0000000..45ca832 --- /dev/null +++ b/scripts/_fix_dylive_browser_launch_lf.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Fix dylive neko-12 browser-launch CRLF/corrupt + start chrome.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +# force LF +raw = LOCAL.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") +assert b"--jitless" in raw + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + + +c = connect() +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-lf.sh", "wb") as f: + f.write(raw) +sftp.chmod("/tmp/browser-launch-lf.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set -euo pipefail +# overwrite ALL browser-launch copies with LF version +for f in /opt/douyinWEB/backend/neko/browser-launch.sh /opt/douyinWEB/backend/neko/browser-launch.sh.bak-sigill*; do + [ -e "$f" ] || continue + cat /tmp/browser-launch-lf.sh > "$f" + chmod 755 "$f" + # strip any leftover CR + sed -i 's/\r$//' "$f" || true +done +file /opt/douyinWEB/backend/neko/browser-launch.sh +head -1 /opt/douyinWEB/backend/neko/browser-launch.sh | od -c | head -2 +grep -n jitless /opt/douyinWEB/backend/neko/browser-launch.sh | head -2 + +# patch mounted inode for neko-12 +INO=$(docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* | awk -v i="$INO" '$1==i{print $NF; exit}') +echo INO=$INO MATCH=$MATCH +cat /tmp/browser-launch-lf.sh > "$MATCH" +sed -i 's/\r$//' "$MATCH" || true +docker exec douyinweb-neko-12 sh -c 'head -1 /etc/neko/browser-launch.sh | od -c | head -2; grep -n jitless /etc/neko/browser-launch.sh | head; sh -n /etc/neko/browser-launch.sh && echo syntax_ok' + +# show last chrome log +docker exec douyinweb-neko-12 sh -c 'tail -50 /var/log/neko/google-chrome.log 2>/dev/null || true' + +# clear locks and start +docker exec douyinweb-neko-12 sh -c ' +rm -f /home/neko/.config/google-chrome/Singleton* /home/neko/.config/chromium/Singleton* 2>/dev/null || true +supervisorctl clear google-chrome || true +supervisorctl update || true +supervisorctl start google-chrome || supervisorctl restart google-chrome +sleep 8 +supervisorctl status google-chrome +' +# if still bad, run launch manually for error +docker exec douyinweb-neko-12 sh -c ' +if ! supervisorctl status google-chrome | grep -q RUNNING; then + echo MANUAL_TRY + su -s /bin/sh neko -c "DISPLAY=:99.0 /etc/neko/browser-launch.sh google-chrome" > /tmp/chrome-manual.log 2>&1 & + sleep 3 + tail -40 /tmp/chrome-manual.log || true + tail -40 /var/log/neko/google-chrome.log || true +fi +curl -sS -m 3 http://127.0.0.1:9222/json/version || echo no_devtools +' +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_fix_dylive_drop_nowasmsimd.py b/scripts/_fix_dylive_drop_nowasmsimd.py new file mode 100644 index 0000000..40361a4 --- /dev/null +++ b/scripts/_fix_dylive_drop_nowasmsimd.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Drop invalid --no-wasm-simd; refresh dylive neko-12 launch + chrome.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +raw = ( + Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") +assert b"--jitless" in raw +assert b"--no-wasm-simd" not in raw + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, +) +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-lf.sh", "wb") as f: + f.write(raw) +sftp.chmod("/tmp/browser-launch-lf.sh", 0o755) +# overwrite canonical host path (remounted after last restart) +with sftp.file("/opt/douyinWEB/backend/neko/browser-launch.sh", "wb") as f: + f.write(raw) +sftp.chmod("/opt/douyinWEB/backend/neko/browser-launch.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set +e +# also overwrite whatever inode container currently has +INO=$(docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +MATCH=$(find /opt /root -xdev -inum "$INO" 2>/dev/null | head -1) +echo CTR_INO=$INO MATCH=$MATCH +if [ -n "$MATCH" ]; then + cat /tmp/browser-launch-lf.sh > "$MATCH" + chmod 755 "$MATCH" +else + # path remount: restart keeps profile volumes + docker restart douyinweb-neko-12 + sleep 12 +fi + +docker exec douyinweb-neko-12 sh -c ' +grep -n "js-flags\|jitless\|no-wasm" /etc/neko/browser-launch.sh | head -5 +sh -n /etc/neko/browser-launch.sh && echo syntax_ok +rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null +supervisorctl restart google-chrome +sleep 12 +supervisorctl status google-chrome +tail -20 /var/log/neko/google-chrome.log 2>/dev/null | grep -E "unrecognized|FATAL|ERROR:.*Aw|DevTools|Listening" || true +curl -sS -m 3 http://127.0.0.1:9222/json/version +# open studio briefly +python3 - < 12000 else out, flush=True) + return code, out + + +def sftp_put(c, local: Path, remote: str): + sftp = c.open_sftp() + sftp.put(str(local), remote) + sftp.close() + print(f"put {local.name} -> {remote}", flush=True) + + +REMOTE = r""" +set -euo pipefail +TS=$(date +%Y%m%d_%H%M%S) + +# --- 1) FRP-aux: remap physical neko HTTP 9200-9207 -> VPS local 19200-19207 --- +UNIT=/etc/systemd/system/dy-frp-http-aux.service +cp -a "$UNIT" "$UNIT.bak.neko_ports_$TS" +cat >"$UNIT" <<'EOF' +[Unit] +Description=dy.nomadro.com FRP-aux tunnels (HTTP+ShellCrash+Neko remapped+S3+ops-neko via :4014) +After=network-online.target frpp.service +Wants=network-online.target + +[Service] +Type=simple +Restart=always +RestartSec=3 +Environment=SSHPASS=4669805 +# Physical assign neko :920x mapped to VPS :1920x so dylive can own :9200-9207 +ExecStart=/usr/bin/sshpass -e ssh -N -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -L 127.0.0.1:18014:127.0.0.1:8014 -L 127.0.0.1:14015:127.0.0.1:4015 -L 127.0.0.1:9999:127.0.0.1:9999 -L 127.0.0.1:19200:127.0.0.1:9200 -L 127.0.0.1:19201:127.0.0.1:9201 -L 127.0.0.1:19202:127.0.0.1:9202 -L 127.0.0.1:19203:127.0.0.1:9203 -L 127.0.0.1:19204:127.0.0.1:9204 -L 127.0.0.1:19205:127.0.0.1:9205 -L 127.0.0.1:19206:127.0.0.1:9206 -L 127.0.0.1:19207:127.0.0.1:9207 -L 127.0.0.1:18200:127.0.0.1:18200 -L 127.0.0.1:18201:127.0.0.1:18201 -L 127.0.0.1:18202:127.0.0.1:18202 -L 127.0.0.1:18203:127.0.0.1:18203 -L 127.0.0.1:18204:127.0.0.1:18204 -L 127.0.0.1:18205:127.0.0.1:18205 -L 127.0.0.1:18206:127.0.0.1:18206 -L 127.0.0.1:18207:127.0.0.1:18207 -L 127.0.0.1:28333:127.0.0.1:8333 -p 4014 eric@127.0.0.1 + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl restart dy-frp-http-aux.service +sleep 2 +systemctl is-active dy-frp-http-aux.service + +# --- 2) Caddy dy.nomadro.com: /neko/1-8 -> 1920x (not dylive 920x) --- +SITE=/etc/caddy/sites/dy.nomadro.com.caddy +cp -a "$SITE" "$SITE.bak.neko_ports_$TS" +python3 - <<'PY' +from pathlib import Path +p = Path("/etc/caddy/sites/dy.nomadro.com.caddy") +text = p.read_text(encoding="utf-8") +# high ports first to avoid partial replace +for i in range(7, -1, -1): + old = f"reverse_proxy 127.0.0.1:{9200+i}" + new = f"reverse_proxy 127.0.0.1:{19200+i}" + text = text.replace(old, new) +p.write_text(text, encoding="utf-8") +print("rewritten neko1-8 proxies to 1920x") +for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1): + if "reverse_proxy" in line and ("1920" in line or ":920" in line) and i < 120: + print(f"{i}:{line}") +PY + +caddy validate --config /etc/caddy/Caddyfile +systemctl reload caddy +systemctl is-active caddy + +# --- 3) Ensure VPS NAT1TO1 for local neko WebRTC --- +# Prefer EnvironmentFile or unit Environment= +APIU=/etc/systemd/system/douyinweb-api.service +cp -a "$APIU" "$APIU.bak.neko_nat_$TS" 2>/dev/null || true +if ! grep -q 'DY_NEKO_NAT1TO1=' "$APIU" 2>/dev/null; then + if grep -q 'Environment=DY_PUBLIC_BASE_URL=' "$APIU"; then + sed -i '/Environment=DY_PUBLIC_BASE_URL=/a Environment=DY_NEKO_NAT1TO1=107.173.30.245' "$APIU" + else + sed -i '/\[Service\]/a Environment=DY_NEKO_NAT1TO1=107.173.30.245' "$APIU" + fi + echo "added DY_NEKO_NAT1TO1 to api unit" +else + echo "DY_NEKO_NAT1TO1 already in api unit" +fi +# clear cached wrong ICE if any +rm -f /opt/douyinWEB/backend/data/neko/nat1to1.txt 2>/dev/null || true + +# --- 4) Deploy host_profile.py --- +install -m 0644 /tmp/host_profile.py /opt/douyinWEB/backend/app/host_profile.py +# youtube_neko compose fallbacks (optional, already uploaded if present) +if [[ -f /tmp/youtube_neko.py ]]; then + install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +fi + +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 3 +systemctl is-active douyinweb-api + +echo '--- ports ---' +ss -lntp | grep -E ':(920[0-7]|1920[0-7]|18014|14015)\b' | head -30 || true +echo '--- health ---' +curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 220; echo +curl -sS -m 8 -o /dev/null -w 'dy_api=%{http_code}\n' https://dy.nomadro.com/api/health +curl -sS -m 8 -o /dev/null -w 'dylive_api=%{http_code}\n' https://dylive.nomadro.com/api/health +""" + + +def main(): + c = ssh() + try: + sftp_put(c, ROOT / "backend/app/host_profile.py", "/tmp/host_profile.py") + sftp_put(c, ROOT / "backend/app/youtube_neko.py", "/tmp/youtube_neko.py") + code, _ = run(c, REMOTE, t=240) + if code != 0: + raise SystemExit(f"remote failed {code}") + + # Start local neko for group with neko_enabled (instance 3) to verify ports free + run( + c, + r""" +set +e +CS=$(mktemp) +curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +# find group with neko_instance_id=3 +GID=$(curl -sS -m 15 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups | python3 -c ' +import sys,json +rows=json.load(sys.stdin) +rows=rows if isinstance(rows,list) else rows.get("groups") or [] +for g in rows: + if int(g.get("neko_instance_id") or 0)==3: + print(g.get("id") or ""); break +') +echo "gid3=$GID" +if [[ -n "$GID" ]]; then + curl -sS -m 120 -b "$CS" -X POST "http://127.0.0.1:8014/api/youtube/assign/groups/${GID}/neko" \ + -H 'Content-Type: application/json' \ + -d '{"action":"start","enabled":true}' | python3 -c 'import sys,json; d=json.load(sys.stdin); print({k:d.get(k) for k in ("ok","error")}); n=d.get("neko") or {}; print("neko", {k:n.get(k) for k in ("id","running","ready","status","studio_url")})' +fi +sleep 2 +docker ps --format '{{.Names}} {{.Status}} {{.Ports}}' | grep douyinweb-neko | head +ss -lntp | grep ':9202' | head +curl -sS -m 8 -o /dev/null -w 'local9202=%{http_code}\n' http://127.0.0.1:9202/ +curl -sS -m 8 -o /dev/null -w 'dylive_neko3=%{http_code}\n' https://dylive.nomadro.com/neko/3/ +curl -sS -m 8 -o /dev/null -w 'dy_neko1=%{http_code}\n' https://dy.nomadro.com/neko/1/ +curl -sS -m 8 -o /dev/null -w 'dy_cn_neko1=%{http_code}\n' https://dy.nomadro.cn/neko/1/ +# inspect env on started container +docker inspect douyinweb-neko-3 --format '{{json .Config.Env}}' 2>/dev/null | tr ',' '\n' | grep -E 'NAT1TO1|BITRATE|MAX_FPS|DESKTOP_SCREEN|BROWSER_PROXY' || true +rm -f "$CS" +""", + t=180, + ) + finally: + c.close() + + print("\n===== public verify =====", flush=True) + with httpx.Client(follow_redirects=False, timeout=25) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/neko/3/", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + ]: + try: + r = cl.get(u) + print(f"{r.status_code} {u}", flush=True) + except Exception as ex: + print(f"ERR {u} {ex}", flush=True) + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_dylive_neko12_chrome_spawn.py b/scripts/_fix_dylive_neko12_chrome_spawn.py new file mode 100644 index 0000000..6872ca4 --- /dev/null +++ b/scripts/_fix_dylive_neko12_chrome_spawn.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Recover dylive neko-12 chrome after FATAL spawn; dedupe key registry.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(3 + i) + raise SystemExit("ssh fail") + + +c = connect() +_i, o, e = c.exec_command( + r""" +set +e +echo '=== chrome supervisor ===' +docker exec douyinweb-neko-12 supervisorctl status +docker exec douyinweb-neko-12 sh -c 'ls -la /var/log/supervisor/ 2>/dev/null; tail -80 /var/log/supervisor/google-chrome*.log 2>/dev/null; tail -80 /var/log/supervisor/chrome*.log 2>/dev/null' +docker exec douyinweb-neko-12 cat /etc/neko/supervisord/google-chrome.conf 2>/dev/null | head -40 +echo '=== try start ===' +# clear profile locks then start +docker exec douyinweb-neko-12 sh -c ' +rm -f /home/neko/.config/google-chrome/Singleton* /home/neko/.config/chromium/Singleton* 2>/dev/null +supervisorctl stop google-chrome +sleep 1 +supervisorctl start google-chrome +sleep 5 +supervisorctl status google-chrome +' +# if still fatal, check command +docker exec douyinweb-neko-12 sh -c ' +ps aux | head -5 +ps aux | grep -i chrome | grep -v grep | head +curl -sS -m 2 http://127.0.0.1:9222/json/version || echo no_devtools +' + +# dedupe registry by youtube_channel_id keeping newest non-empty key +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import sqlite3, time +from app.db import _connect, _lock +from app import yt_stream_key_db +with _lock: + conn = _connect() + yt_stream_key_db.ensure_stream_key_tables(conn) + rows = conn.execute('SELECT id, youtube_channel_id, stream_key, updated_at, name FROM yt_stream_key_registry').fetchall() + by = {} + for r in rows: + ycid = (r[1] or '').strip() or f'__id__{r[0]}' + prev = by.get(ycid) + if prev is None: + by[ycid] = r + continue + # prefer non-empty key, then newer updated_at + def score(x): + return (1 if (x[2] or '').strip() else 0, float(x[3] or 0)) + if score(r) >= score(prev): + by[ycid] = r + keep = {r[0] for r in by.values()} + deleted = 0 + for r in rows: + if r[0] not in keep: + conn.execute('DELETE FROM yt_stream_key_registry WHERE id=?', (r[0],)) + deleted += 1 + conn.commit() + total = conn.execute('SELECT COUNT(*) FROM yt_stream_key_registry').fetchone()[0] + print('dedupe_deleted', deleted, 'total', total) + conn.close() +print(yt_stream_key_db.list_entries(include_secret=False)) +PY + +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_fix_dylive_neko12_remount_launch.py b/scripts/_fix_dylive_neko12_remount_launch.py new file mode 100644 index 0000000..825e483 --- /dev/null +++ b/scripts/_fix_dylive_neko12_remount_launch.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Find neko-12 bind inode and fix browser-launch; start chrome.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +raw = ( + Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, +) +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-lf.sh", "wb") as f: + f.write(raw) +sftp.chmod("/tmp/browser-launch-lf.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set +e +INO=$(docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +echo CTR_INO=$INO +echo 'find host:' +find /opt /root /tmp /var -xdev -inum "$INO" 2>/dev/null +MATCH=$(find /opt /root -xdev -inum "$INO" 2>/dev/null | head -1) +echo MATCH=$MATCH +if [ -n "$MATCH" ]; then + cat /tmp/browser-launch-lf.sh > "$MATCH" + sed -i 's/\r$//' "$MATCH" + chmod 755 "$MATCH" + echo overwritten +else + echo 'NO_MATCH — remount via docker restart (not recreate)' + # Ensure canonical path is good + cat /tmp/browser-launch-lf.sh > /opt/douyinWEB/backend/neko/browser-launch.sh + sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh + chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh + # restart container keeps volumes/profile; remounts file by path + docker restart douyinweb-neko-12 + sleep 12 +fi + +docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh; head -1 /etc/neko/browser-launch.sh | od -c | head -1; grep -n jitless /etc/neko/browser-launch.sh | head -1; sh -n /etc/neko/browser-launch.sh && echo syntax_ok' +docker exec douyinweb-neko-12 sh -c ' +rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null +supervisorctl start google-chrome 2>/dev/null || supervisorctl restart google-chrome +sleep 10 +supervisorctl status +tail -30 /var/log/neko/google-chrome.log 2>/dev/null +curl -sS -m 3 http://127.0.0.1:9222/json/version || echo no_devtools +' +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_fix_dylive_neko12_sigill.py b/scripts/_fix_dylive_neko12_sigill.py new file mode 100644 index 0000000..1028308 --- /dev/null +++ b/scripts/_fix_dylive_neko12_sigill.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Recover dylive neko-12 after SIGILL: free mem, patch chrome flags, restart browser, reopen Studio.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +PASS = "Xiao4669805" +STUDIO = "https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=180): + print(f"\n===== {cmd[:90].replace(chr(10),' ')} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return o.channel.recv_exit_status(), out + + +c = ssh() + +# 1) How is browser-launch mounted + drop caches if safe +run( + c, + r""" +set +e +echo '=== mounts ===' +docker inspect douyinweb-neko-12 --format '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}' | head -40 +echo '=== mem before ===' +free -h | head -3 +# drop caches (safe) to help chrome restart +sync; echo 3 > /proc/sys/vm/drop_caches +free -h | head -3 +# list heavy processes +ps aux --sort=-rss | head -15 +""", +) + +# 2) Patch host-side browser-launch if bind-mounted; also patch inside container as fallback +run( + c, + r""" +set -euo pipefail +SRC='' +for p in \ + /opt/douyinWEB/backend/neko/browser-launch.sh \ + /opt/douyinWEB/neko/browser-launch.sh +do + if [ -f "$p" ]; then SRC="$p"; break; fi +done +echo "SRC=$SRC" +if [ -n "$SRC" ]; then + cp -a "$SRC" "${SRC}.bak-sigill-$(date +%s)" + # Harden js-flags against WASM/AVX512 SIGILL on Studio pages; raise renderer heap a bit + python3 - </dev/null || true +done +docker exec douyinweb-neko-12 sh -c 'find / -name browser-launch.sh 2>/dev/null | head' +""", +) + +c.close() +print("PHASE1_DONE") diff --git a/scripts/_fix_dylive_neko12_sigill_deploy.py b/scripts/_fix_dylive_neko12_sigill_deploy.py new file mode 100644 index 0000000..a938a83 --- /dev/null +++ b/scripts/_fix_dylive_neko12_sigill_deploy.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Deploy SIGILL chrome flags to dylive + recover neko-12 Studio tab.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.50.68" +# correct dylive: +HOST = "107.173.30.245" +PASS = "Xiao4669805" +REMOTE = "/opt/douyinWEB/backend/neko/browser-launch.sh" +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +STUDIO = "https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" + + +def main() -> None: + assert LOCAL.is_file(), LOCAL + text = LOCAL.read_text(encoding="utf-8") + assert "no-wasm-simd" in text, "local patch missing" + assert "WebAssemblySimd" in text, "local patch missing" + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + bak = f"{REMOTE}.bak-sigill-{int(time.time())}" + try: + sftp.stat(REMOTE) + sftp.rename(REMOTE, bak) + print("backed_up", bak) + except OSError as e: + print("no_bak", e) + + tmp = "/tmp/browser-launch-sigill.sh" + with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) + sftp.chmod(tmp, 0o755) + sftp.close() + + def run(cmd: str, t: int = 180) -> str: + print("\n=====", cmd[:80].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return out + + run(f"cp -a {tmp} {REMOTE} && grep -n 'no-wasm-simd\\|WebAssemblySimd' {REMOTE}") + run( + r""" +set +e +sync; echo 3 > /proc/sys/vm/drop_caches +free -h | head -3 +docker exec douyinweb-neko-12 grep -n 'no-wasm-simd\|WebAssemblySimd' /etc/neko/browser-launch.sh +docker exec douyinweb-neko-12 supervisorctl restart google-chrome +sleep 10 +docker exec douyinweb-neko-12 supervisorctl status google-chrome +""" + ) + run( + rf""" +docker exec douyinweb-neko-12 python3 - <<'PY' +import json, urllib.request, time +STUDIO = "{STUDIO}" +for i in range(40): + try: + with urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=2) as r: + print("devtools", r.status) + break + except Exception: + time.sleep(1) +else: + raise SystemExit("devtools_fail") + +def get(url, method=None): + req = urllib.request.Request(url, method=method) if method else url + with urllib.request.urlopen(req, timeout=10) as r: + return r.read() + +# open studio tab +opened = False +for meth in ("PUT", "GET"): + try: + body = get("http://127.0.0.1:9222/json/new?" + STUDIO, method=meth) + print("new", meth, body[:180]) + opened = True + break + except Exception as e: + print("new_fail", meth, e) +if not opened: + raise SystemExit("cannot open studio tab") +time.sleep(6) +tabs = json.loads(get("http://127.0.0.1:9222/json/list")) +for t in tabs: + if t.get("type") == "page": + print("TAB", (t.get("title") or "")[:70], "|", (t.get("url") or "")[:120]) +PY +free -h | head -3 +dmesg -T 2>/dev/null | grep -iE 'invalid opcode|oom-kill' | tail -8 +""" + ) + c.close() + print("DONE") + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_dylive_neko12_sigill_inode.py b/scripts/_fix_dylive_neko12_sigill_inode.py new file mode 100644 index 0000000..2dee2e9 --- /dev/null +++ b/scripts/_fix_dylive_neko12_sigill_inode.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Fix Docker file-bind inode trap: patch the inode neko-12 still mounts, or recreate.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +text = LOCAL.read_text(encoding="utf-8") +assert "no-wasm-simd" in text + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +sftp = c.open_sftp() + + +def run(cmd: str, t: int = 300) -> str: + print("\n=====", cmd[:100].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return out + + +# Compare inodes / hashes +run( + r""" +set +e +echo HOST_CUR: +ls -li /opt/douyinWEB/backend/neko/browser-launch.sh +md5sum /opt/douyinWEB/backend/neko/browser-launch.sh +echo HOST_BAKS: +ls -li /opt/douyinWEB/backend/neko/browser-launch.sh.bak-sigill* 2>/dev/null | tail -10 +echo CTR: +docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh; md5sum /etc/neko/browser-launch.sh; grep -n max-old /etc/neko/browser-launch.sh' +""" +) + +# Write patched bytes into EVERY bak + current path (overwrite in place, no rename) +tmp = "/tmp/browser-launch-final.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) + +run( + rf""" +set -euo pipefail +# Overwrite current path in-place (same inode if possible via cat redirect onto existing) +# First: identify which host inode matches container +CTR_INO=$(docker exec douyinweb-neko-12 sh -c "ls -li /etc/neko/browser-launch.sh" | awk '{{print $1}}') +echo CTR_INO=$CTR_INO +HOST_MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$CTR_INO" '$1==i {{print $NF; exit}}') +echo HOST_MATCH=$HOST_MATCH +if [ -n "$HOST_MATCH" ]; then + # in-place overwrite keeping inode: use dd/cat truncating same file + cat {tmp} > "$HOST_MATCH" + echo overwritten_match + ls -li "$HOST_MATCH" + md5sum "$HOST_MATCH" +fi +# also ensure canonical path has content (may be different inode) +cat {tmp} > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +echo AFTER_CTR: +docker exec douyinweb-neko-12 sh -c 'ls -li /etc/neko/browser-launch.sh; grep -n "no-wasm-simd\|WebAssemblySimd\|max-old" /etc/neko/browser-launch.sh' +""" +) + +# If container still stale, recreate neko-12 via API helper / compose +out = run( + r""" +set +e +if docker exec douyinweb-neko-12 grep -q no-wasm-simd /etc/neko/browser-launch.sh; then + echo PATCH_VISIBLE +else + echo PATCH_NOT_VISIBLE_RECREATE + cd /opt/douyinWEB/backend + set -a; source /etc/douyinweb.env; set +a + ./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +# recreate only instance 12 if API exists +for name in ("recreate_instance", "restart_instance", "ensure_instance"): + fn = getattr(yn, name, None) + print("has", name, bool(fn)) +# force recreate via docker compose +import subprocess +from pathlib import Path +cp = yn._compose_path() +print("compose", cp) +# docker compose up -d --force-recreate this service +svc = None +for cand in ("neko-12", "douyinweb-neko-12", "neko_12"): + pass +# inspect compose service names +text = Path(cp).read_text(encoding="utf-8") +for line in text.splitlines(): + if "neko-12" in line or "container_name: douyinweb-neko-12" in line: + print("line", line.strip()[:120]) +PY + # docker compose force recreate by container name + COMPOSE=$(docker inspect douyinweb-neko-12 --format '{{index .Config.Labels "com.docker.compose.project.working_dir"}}') + PROJ=$(docker inspect douyinweb-neko-12 --format '{{index .Config.Labels "com.docker.compose.project"}}') + SVC=$(docker inspect douyinweb-neko-12 --format '{{index .Config.Labels "com.docker.compose.service"}}') + echo COMPOSE=$COMPOSE PROJ=$PROJ SVC=$SVC + if [ -n "$COMPOSE" ] && [ -n "$SVC" ]; then + cd "$COMPOSE" + # keep profile volume — just recreate container to remount file inode + docker compose -p "$PROJ" up -d --force-recreate --no-deps "$SVC" + else + docker stop douyinweb-neko-12 + docker rm douyinweb-neko-12 + # regenerate via ensure_capacity + cd /opt/douyinWEB/backend + set -a; source /etc/douyinweb.env; set +a + ./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +print(yn.ensure_capacity(12, start_instances={12}, reconcile_running=True)) +PY + fi + sleep 15 + docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' + docker exec douyinweb-neko-12 grep -n 'no-wasm-simd\|max-old' /etc/neko/browser-launch.sh +fi +""" +) + +# restart chrome + open studio +run( + r""" +set +e +docker exec douyinweb-neko-12 supervisorctl restart google-chrome || true +sleep 12 +docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "js-flags|wasm|WebAssembly|max-old"; break ;; + esac +done' +docker exec douyinweb-neko-12 python3 -c ' +import json,urllib.request,time +S="https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" +for i in range(40): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version",timeout=2).read(); print("devtools_ok"); break + except Exception: + time.sleep(1) +else: + raise SystemExit("no_devtools") +req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") +print("new", urllib.request.urlopen(req,timeout=15).read()[:100]) +time.sleep(8) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print("TAB",(t.get("title") or "")[:70], "|", (t.get("url") or "")[:130]) +' +free -h | head -3 +""" +) +sftp.close() +c.close() +print("DONE") diff --git a/scripts/_fix_dylive_neko12_sigill_mount.py b/scripts/_fix_dylive_neko12_sigill_mount.py new file mode 100644 index 0000000..4d7b050 --- /dev/null +++ b/scripts/_fix_dylive_neko12_sigill_mount.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Find real browser-launch mount source on dylive and force-patch + restart chrome.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +text = LOCAL.read_text(encoding="utf-8") +assert "no-wasm-simd" in text + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + + +def run(cmd: str, t: int = 120) -> str: + print("\n=====", cmd[:90].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-10000:] if len(out) > 10000 else out, flush=True) + return out + + +out = run( + "docker inspect douyinweb-neko-12 --format '{{range .Mounts}}{{.Source}}|{{.Destination}}|{{.Mode}}{{println}}{{end}}'" +) +# find browser-launch source +src = "" +for line in out.splitlines(): + if "browser-launch" in line: + src = line.split("|")[0].strip() + print("FOUND_SRC", src) + +if not src: + # fallback search + out2 = run("find /opt /root /home -name browser-launch.sh 2>/dev/null | head -20") + for line in out2.splitlines(): + if line.strip().endswith("browser-launch.sh"): + src = line.strip() + break + +if not src: + raise SystemExit("no browser-launch source") + +sftp = c.open_sftp() +bak = f"{src}.bak-sigill2-{int(time.time())}" +try: + sftp.rename(src, bak) + print("bak", bak) +except OSError as e: + print("rename_err", e) + # copy then overwrite + run(f"cp -a '{src}' '{bak}' || true") + +tmp = "/tmp/browser-launch-sigill2.sh" +with sftp.file(tmp, "wb") as f: + f.write(text.encode("utf-8")) +sftp.chmod(tmp, 0o755) +sftp.close() + +run(f"cp -a {tmp} '{src}' && ls -la '{src}' && grep -n 'no-wasm-simd\\|WebAssemblySimd\\|max-old-space' '{src}'") +run( + r""" +set +e +docker exec douyinweb-neko-12 grep -n 'no-wasm-simd\|WebAssemblySimd\|max-old-space' /etc/neko/browser-launch.sh +docker exec douyinweb-neko-12 supervisorctl restart google-chrome +sleep 12 +docker exec douyinweb-neko-12 supervisorctl status google-chrome +docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "js-flags|wasm|WebAssembly|max-old" ; break ;; + esac +done' +# reopen studio +docker exec douyinweb-neko-12 python3 -c ' +import json,urllib.request,time +S="https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" +for i in range(30): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version",timeout=2).read(); break + except Exception: + time.sleep(1) +req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+S, method="PUT") +print(urllib.request.urlopen(req,timeout=15).read()[:120]) +time.sleep(6) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + print("TAB",(t.get("title") or "")[:70], "|", (t.get("url") or "")[:120]) +' +""" +) +c.close() +print("DONE") diff --git a/scripts/_fix_dylive_neko2_tm_scripts.py b/scripts/_fix_dylive_neko2_tm_scripts.py new file mode 100644 index 0000000..088e93a --- /dev/null +++ b/scripts/_fix_dylive_neko2_tm_scripts.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Repair dylive neko-2 Tampermonkey userscripts from neko-19 (no container recreate).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e) + time.sleep(2) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set -euo pipefail +SRC=/opt/douyinWEB/backend/data/neko/profiles/19/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo +DST=/opt/douyinWEB/backend/data/neko/profiles/2/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo + +echo "=== before ===" +grep -a -c "YouTube Studio Auto Dismiss" "$SRC" 2>/dev/null || echo "src_markers=0" +grep -a -c "YouTube Studio Auto Dismiss" "$DST" 2>/dev/null || echo "dst_markers=0" +du -sb "$SRC" "$DST" 2>/dev/null || true + +# verify provisioning server inside neko-2 +docker exec douyinweb-neko-2 sh -c 'curl -sS -m 3 http://127.0.0.1:18080/tampermonkey-provisioning.json | head -c 120; echo' + +echo "=== stop chrome on neko-2 ===" +docker exec douyinweb-neko-2 supervisorctl stop google-chrome || true +sleep 2 + +echo "=== copy TM storage 19 -> 2 ===" +mkdir -p "$(dirname "$DST")" +rm -rf "$DST.bak-empty" 2>/dev/null || true +if [ -d "$DST" ]; then mv "$DST" "$DST.bak-empty"; fi +cp -a "$SRC" "$DST" +rm -f "$DST/LOCK" 2>/dev/null || true +chown -R 1000:1000 "$DST" 2>/dev/null || chown -R neko:neko "$DST" 2>/dev/null || true +# also ensure host uid matches container +docker exec douyinweb-neko-2 sh -c 'chown -R neko:neko "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" 2>/dev/null; rm -f "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/LOCK"' + +echo "=== start chrome ===" +docker exec douyinweb-neko-2 sh -c 'rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null; supervisorctl start google-chrome' +sleep 12 +docker exec douyinweb-neko-2 supervisorctl status google-chrome + +echo "=== after markers ===" +docker exec douyinweb-neko-2 sh -c ' +python3 - <<"PY" +import os,re +p="/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +blob=b"" +for root,_,fs in os.walk(p): + for f in fs: + try: blob+=open(os.path.join(root,f),"rb").read() + except: pass +print("blob",len(blob),"markers",len(re.findall(r"YouTube Studio Auto Dismiss", blob.decode("latin1","ignore")))) +PY +curl -sS -m 3 http://127.0.0.1:9222/json/version | head -c 100; echo +python3 - <<"PY" +import json,urllib.request +tabs=json.load(urllib.request.urlopen("http://127.0.0.1:9222/json",timeout=5)) +print("tabs",len(tabs)) +for t in tabs: + if "dhdgff" in (t.get("url") or "") or "studio.youtube" in (t.get("url") or ""): + print(t.get("type"), (t.get("url") or "")[:90]) +PY +' +echo FIX_DONE +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_dylive_neko6_chrome.py b/scripts/_fix_dylive_neko6_chrome.py new file mode 100644 index 0000000..bf30501 --- /dev/null +++ b/scripts/_fix_dylive_neko6_chrome.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Recover dylive neko-6 Chrome FATAL — no container recreate.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +raw = LOCAL.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") +assert b"--jitless" in raw + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +c = connect() +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-neko6.sh", "wb") as f: + f.write(raw) +sftp.chmod("/tmp/browser-launch-neko6.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set -euo pipefail +NAME=douyinweb-neko-6 + +# sync host + any bak inodes +for f in /opt/douyinWEB/backend/neko/browser-launch.sh /opt/douyinWEB/backend/neko/browser-launch.sh.bak-sigill*; do + [ -e "$f" ] || continue + cat /tmp/browser-launch-neko6.sh > "$f" + chmod 755 "$f" + sed -i 's/\r$//' "$f" || true +done + +# patch the exact inode mounted into this container +INO=$(docker exec "$NAME" sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +MATCH=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$INO" '$1==i{print $NF; exit}') +echo INO=$INO MATCH=$MATCH +if [ -n "${MATCH:-}" ] && [ -e "$MATCH" ]; then + cat /tmp/browser-launch-neko6.sh > "$MATCH" + sed -i 's/\r$//' "$MATCH" || true +else + # fallback: docker cp into running container (persists until recreate — ok) + docker cp /tmp/browser-launch-neko6.sh "$NAME":/etc/neko/browser-launch.sh + docker exec "$NAME" chmod 755 /etc/neko/browser-launch.sh +fi + +docker exec "$NAME" sh -c 'head -1 /etc/neko/browser-launch.sh | od -c | head -2; grep -n jitless /etc/neko/browser-launch.sh | head -2; sh -n /etc/neko/browser-launch.sh && echo syntax_ok' +docker exec "$NAME" sh -c 'tail -60 /var/log/neko/google-chrome.log 2>/dev/null || echo no_chrome_log' + +# kill leftover chrome from manual probe; clear locks; fix cache dir perms +docker exec "$NAME" sh -c ' +pkill -u neko -f "[g]oogle-chrome" 2>/dev/null || true +pkill -u neko -f "[c]hrome" 2>/dev/null || true +sleep 1 +rm -f /home/neko/.config/google-chrome/Singleton* /home/neko/.config/chromium/Singleton* 2>/dev/null || true +mkdir -p "/home/neko/.config/google-chrome/Default/Shared Dictionary/cache" +chown -R neko:neko /home/neko/.config/google-chrome 2>/dev/null || true +supervisorctl stop google-chrome || true +sleep 1 +supervisorctl clear google-chrome || true +supervisorctl start google-chrome +sleep 10 +supervisorctl status +' + +docker exec "$NAME" sh -c ' +curl -sS -m 5 http://127.0.0.1:9222/json/version | head -c 500; echo +# count chrome procs via /proc +n=0 +for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null || true) + case "$cmd" in *chrome*) n=$((n+1));; esac +done +echo chrome_procs=$n +' + +# ensure group can open neko if needed (do NOT recreate) +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db +for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): + if int(g.get("neko_instance_id") or 0) == 6: + print("group", g.get("name"), "neko_enabled", g.get("neko_enabled")) +PY + +docker ps --filter name=douyinweb-neko-6 --format '{{.Names}} {{.Status}}' +free -m | head -2 +echo NEKO6_CHROME_DONE +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_dylive_neko6_chrome2.py b/scripts/_fix_dylive_neko6_chrome2.py new file mode 100644 index 0000000..caa8c91 --- /dev/null +++ b/scripts/_fix_dylive_neko6_chrome2.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Find neko-6 browser-launch mount and restart chrome.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +raw = LOCAL.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, + ) + return c + + +c = connect() +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-neko6.sh", "wb") as f: + f.write(raw) +sftp.chmod("/tmp/browser-launch-neko6.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set +e +NAME=douyinweb-neko-6 +echo '=== mounts browser-launch ===' +docker inspect "$NAME" --format '{{range .Mounts}}{{println .Source "->" .Destination}}{{end}}' | grep -E 'browser-launch|neko' | head -40 +echo +echo '=== find host file by inode ===' +INO=$(docker exec "$NAME" sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +echo INO=$INO +# search common roots +find /opt/douyinWEB /var/lib/docker -xdev -inum "$INO" 2>/dev/null | head -10 +# also find via mountinfo +docker exec "$NAME" sh -c 'cat /proc/self/mountinfo | grep browser-launch; ls -li /etc/neko/browser-launch.sh' +echo +# write to known host path AND any found inode +cat /tmp/browser-launch-neko6.sh > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh +sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh +for f in $(find /opt/douyinWEB -xdev -inum "$INO" 2>/dev/null); do + echo writing $f + cat /tmp/browser-launch-neko6.sh > "$f" + sed -i 's/\r$//' "$f" +done +# if container file is bind-mounted from compose volume path +SRC=$(docker inspect "$NAME" --format '{{range .Mounts}}{{if eq .Destination "/etc/neko/browser-launch.sh"}}{{.Source}}{{end}}{{end}}') +echo SRC=$SRC +if [ -n "$SRC" ] && [ -e "$SRC" ]; then + cat /tmp/browser-launch-neko6.sh > "$SRC" + sed -i 's/\r$//' "$SRC" + echo wrote_src +fi + +docker exec "$NAME" sh -c 'grep -n jitless /etc/neko/browser-launch.sh | head -3; sh -n /etc/neko/browser-launch.sh && echo syntax_ok; file /etc/neko/browser-launch.sh; head -1 /etc/neko/browser-launch.sh | od -c | head -2' +echo '=== chrome log before ===' +docker exec "$NAME" sh -c 'tail -40 /var/log/neko/google-chrome.log 2>/dev/null' +echo '=== restart chrome ===' +docker exec "$NAME" sh -c ' +pkill -u neko -f google-chrome 2>/dev/null +pkill -u neko -f "/opt/google/chrome" 2>/dev/null +sleep 1 +rm -f /home/neko/.config/google-chrome/SingletonLock /home/neko/.config/google-chrome/SingletonSocket /home/neko/.config/google-chrome/SingletonCookie 2>/dev/null +mkdir -p "/home/neko/.config/google-chrome/Default/Shared Dictionary/cache" +chown -R neko:neko /home/neko/.config/google-chrome 2>/dev/null +supervisorctl stop google-chrome +sleep 1 +supervisorctl start google-chrome +sleep 12 +supervisorctl status google-chrome +supervisorctl status +' +echo '=== cdp ===' +docker exec "$NAME" sh -c 'curl -sS -m 5 http://127.0.0.1:9222/json/version; echo' +echo '=== log after ===' +docker exec "$NAME" sh -c 'tail -30 /var/log/neko/google-chrome.log 2>/dev/null' +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_dylive_neko6_perms.py b/scripts/_fix_dylive_neko6_perms.py new file mode 100644 index 0000000..4f13343 --- /dev/null +++ b/scripts/_fix_dylive_neko6_perms.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +_i, o, e = c.exec_command( + r""" +set +e +chown -R 1000:1000 /opt/douyinWEB/backend/data/neko/profiles/6 +ls -la /opt/douyinWEB/backend/data/neko/profiles/6/Default | sed -n '1,15p' +docker exec douyinweb-neko-6 sh -c 'id neko; ls -la /home/neko/.config/google-chrome/Default | sed -n "1,12p"; supervisorctl status google-chrome; curl -sS -m 3 http://127.0.0.1:9222/json/version' +echo +docker ps --filter name=douyinweb-neko-6 --format '{{.Names}} {{.Status}}' +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_dylive_neko_all_404.py b/scripts/_fix_dylive_neko_all_404.py new file mode 100644 index 0000000..ce0bb86 --- /dev/null +++ b/scripts/_fix_dylive_neko_all_404.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose + fix dylive.nomadro.com /neko/* 404 (all local Nekos).""" +import re +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*VPS[:2], username=VPS[2], password=VPS[3], timeout=40, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, timeout=90): + _i, o, e = c.exec_command(cmd, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def main() -> None: + print("=== public ===") + with httpx.Client(timeout=15, follow_redirects=False) as client: + for u in [ + "https://dylive.nomadro.com/neko/1", + "https://dylive.nomadro.com/neko/1/", + "https://dylive.nomadro.com/neko/7", + "https://dylive.nomadro.com/neko/7/", + ]: + try: + r = client.get(u) + print(u, r.status_code, "loc="+r.headers.get("location", ""), "ct="+r.headers.get("content-type","")[:30]) + except Exception as ex: + print(u, ex) + + c = ssh() + print(run(c, r""" +echo '=== find dylive caddy ===' +ls -la /etc/caddy/sites/ 2>/dev/null +for f in /etc/caddy/sites/*; do + if grep -q 'dylive.nomadro.com' "$f" 2>/dev/null; then echo FOUND "$f"; fi +done +echo '=== neko handles ===' +grep -nE 'neko|920[0-9]|9199' /etc/caddy/sites/* 2>/dev/null | head -100 +echo '=== local neko ports ===' +ss -lntp | grep -E ':920[0-9]|:9199' | head -20 +docker ps --format '{{.Names}}' | grep douyinweb-neko | sort +curl -sS -m 3 -o /dev/null -w 'p9200=%{http_code} ' http://127.0.0.1:9200/ || true +curl -sS -m 3 -o /dev/null -w 'p9206=%{http_code}\n' http://127.0.0.1:9206/ || true +""")) + + # locate site file + out = run(c, "grep -l 'dylive.nomadro.com' /etc/caddy/sites/* 2>/dev/null | head -1") + site = out.strip().splitlines()[-1].strip() if out.strip() else "" + print("SITE_FILE", site) + if not site: + out2 = run(c, "grep -lR 'dylive.nomadro.com' /etc/caddy /opt/douyinWEB 2>/dev/null | head -10") + print("SEARCH", out2) + c.close() + return + + text = run(c, f"cat {site}") + print("=== site head ===") + print("\n".join(text.splitlines()[:40])) + print("=== neko-related lines ===") + for i, line in enumerate(text.splitlines(), 1): + if "neko" in line.lower() or re.search(r"920\d|9199", line): + print(f"{i}:{line}") + + # Desired block: redirect bare /neko/N -> /neko/N/ ; proxy all /neko/N/* to 127.0.0.1:9200+(N-1) + # Prefer unlimited pattern like physical gateway if present on :9199, else per-port reverse_proxy for 1..64 + + has_gw = "9199" in run(c, "ss -lntp | grep 9199 || true") + print("gateway9199", has_gw) + + # Build replacement: remove old per-instance neko handles, insert unlimited block + NEKO_BLOCK = r''' + # Neko: bare /neko/N -> /neko/N/ then proxy to localhost 9200+(N-1) + @nekoBare path_regexp nekoBare ^/neko/([0-9]+)$ + redir @nekoBare /neko/{re.nekoBare.1}/ 308 + @nekoPath path_regexp nekoPath ^/neko/([0-9]+)(/.*)?$ + handle @nekoPath { + reverse_proxy {http.request.uri} { + to localhost:9200 localhost:9201 localhost:9202 localhost:9203 localhost:9204 localhost:9205 localhost:9206 localhost:9207 localhost:9208 localhost:9209 localhost:9210 localhost:9211 localhost:9212 localhost:9213 localhost:9214 localhost:9215 + lb_policy cookie + } + } +''' + # Caddy can't easily map N->port with lb like that. Use handle_path per instance OR a small gateway. + # Best: use map + rewrite or individual handle_path for 1..32. + + lines = [] + lines.append("\t# --- neko unlimited (auto) ---") + lines.append("\t@nekoBare path_regexp nekoBare ^/neko/([0-9]+)$") + lines.append("\tredir @nekoBare /neko/{re.nekoBare.1}/ 308") + for i in range(1, 33): + port = 9200 + i - 1 + lines.append(f"\thandle_path /neko/{i}/* {{") + lines.append(f"\t\treverse_proxy 127.0.0.1:{port} {{") + lines.append("\t\t\theader_up Host {host}") + lines.append("\t\t\theader_up X-Forwarded-Proto {scheme}") + lines.append("\t\t\theader_up X-Forwarded-Host {host}") + lines.append("\t\t}") + lines.append("\t}") + neko_block = "\n".join(lines) + "\n" + + # Strip existing neko handle blocks + cleaned = text + # remove @neko / redir neko / handle_path /neko/N / handle /neko/N + cleaned = re.sub(r"\n\t@nekoBare[\s\S]*?\n\tredir @nekoBare[^\n]*\n", "\n", cleaned) + cleaned = re.sub(r"\n\thandle_path /neko/\d+/\* \{[\s\S]*?\n\t\}\n", "\n", cleaned) + cleaned = re.sub(r"\n\thandle /neko/\d+ \{[\s\S]*?\n\t\}\n", "\n", cleaned) + cleaned = re.sub(r"\n\t# --- neko unlimited \(auto\) ---[\s\S]*?(?=\n\t(?:handle|@|#)|$)", "\n", cleaned) + # also remove older # Neko comments blocks carefully - if gateway style + cleaned = re.sub( + r"\n\t@neko path /neko /neko/\*[\s\S]*?\n\thandle @neko \{[\s\S]*?\n\t\}\n", + "\n", + cleaned, + ) + + # Insert neko block after opening brace of site + m = re.search(r"(dylive\.nomadro\.com\s*\{)", cleaned) + if not m: + print("NO_SITE_BRACE") + c.close() + return + insert_at = m.end() + new_text = cleaned[:insert_at] + "\n" + neko_block + cleaned[insert_at:] + + # backup + write via sftp then install + bak = f"{site}.bak_neko_{int(time.time())}" + sftp = c.open_sftp() + with sftp.file("/tmp/dylive_neko_fix.caddy", "w") as f: + f.write(new_text) + sftp.close() + print(run(c, f""" +set -e +cp -a {site} {bak} +cat /tmp/dylive_neko_fix.caddy > {site} +# validate +caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20 +caddy reload --config /etc/caddy/Caddyfile 2>&1 | tail -10 +echo RELOADED +""")) + + time.sleep(1) + print("=== verify ===") + with httpx.Client(timeout=15, follow_redirects=False) as client: + for u in [ + "https://dylive.nomadro.com/neko/1", + "https://dylive.nomadro.com/neko/1/", + "https://dylive.nomadro.com/neko/7", + "https://dylive.nomadro.com/neko/7/", + "https://dylive.nomadro.com/neko/8/", + ]: + r = client.get(u) + print(u, r.status_code, "loc="+r.headers.get("location",""), "snip="+r.text[:60].replace("\n"," ")) + # follow + with httpx.Client(timeout=15, follow_redirects=True) as client: + for u in ["https://dylive.nomadro.com/neko/7", "https://dylive.nomadro.com/neko/1/"]: + r = client.get(u) + print("FOLLOW", u, r.status_code, r.url, r.text[:50].replace("\n"," ")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_dylive_oauth_redirect.py b/scripts/_fix_dylive_oauth_redirect.py new file mode 100644 index 0000000..86490f7 --- /dev/null +++ b/scripts/_fix_dylive_oauth_redirect.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, +) +# write then run separately with longer timeout +sftp = c.open_sftp() +with sftp.open("/tmp/fix_oauth_redir.py", "w") as f: + f.write( + """ +import json, sqlite3 +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +uri="https://dylive.nomadro.com/api/shorts/oauth/callback" +c.execute( + "INSERT INTO kv_settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", + ("shorts_oauth_redirect_uri", json.dumps(uri)), +) +c.commit() +print(json.loads(c.execute("select value from kv_settings where key='shorts_oauth_redirect_uri'").fetchone()[0])) +c.close() +""" + ) +sftp.close() +_i, o, e = c.exec_command("python3 /tmp/fix_oauth_redir.py", timeout=30) +print("fix:", (o.read() + e.read()).decode("utf-8", "replace")) +_i, o, e = c.exec_command("systemctl restart douyinweb-api", timeout=90) +o.channel.recv_exit_status() +print("restart:", (o.read() + e.read()).decode("utf-8", "replace")) +_i, o, e = c.exec_command( + "sleep 3; systemctl is-active douyinweb-api; curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health", + timeout=40, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_neko3_chrome_dual.py b/scripts/_fix_neko3_chrome_dual.py new file mode 100644 index 0000000..de886a0 --- /dev/null +++ b/scripts/_fix_neko3_chrome_dual.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Hard-kill all chrome PIDs inside neko-3 (no pkill), then single restart.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +FIX = r"""#!/bin/bash +set -e +N=douyinweb-neko-3 +docker exec "$N" supervisorctl stop google-chrome || true +sleep 1 +docker exec -i "$N" python3 - <<'PY' +import os, signal, time +killed=[] +for _ in range(3): + for pid in list(os.listdir("/proc")): + if not pid.isdigit(): + continue + try: + raw=open(f"/proc/{pid}/cmdline","rb").read() + except Exception: + continue + if not raw: + continue + if b"google-chrome" in raw or b"/opt/google/chrome" in raw: + try: + os.kill(int(pid), signal.SIGKILL) + killed.append(pid) + except Exception as e: + print("kill_fail", pid, e) + time.sleep(0.5) +print("killed", killed) +# leftover mains? +left=[] +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if b"google-chrome" in raw or b"/opt/google/chrome/chrome" in raw: + left.append((pid, raw.replace(b"\0",b" ").decode()[:80])) +print("left", left) +PY +docker exec "$N" bash -lc 'rm -f /home/neko/.config/google-chrome/SingletonCookie /home/neko/.config/google-chrome/SingletonLock /home/neko/.config/google-chrome/SingletonSocket /home/neko/.config/google-chrome/SingletonStartupLock /home/neko/.config/google-chrome/lockfile /home/neko/.config/google-chrome/DevToolsActivePort 2>/dev/null; true' +docker exec "$N" supervisorctl start google-chrome +sleep 20 +docker exec "$N" supervisorctl status google-chrome +docker exec -i "$N" python3 - <<'PY' +import json, os, urllib.request +from pathlib import Path +mains=[] +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains.append(pid) + print("chrome_main", pid) + for part in raw.split(b"\0"): + if b"load-extension" in part: + print(" ", part.decode()[:220]) +print("main_count", len(mains)) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw), "tabs", len(tabs)) +for t in tabs: + u=t.get("url") or "" + if "extension" in u or "tampermonkey" in u or t.get("type") in ("service_worker","page"): + if "doubleclick" in u or "recaptcha" in u: continue + print(" ", t.get("type"), u[:130]) +les=Path("/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log") +print("auto_dismiss", "YouTube Studio Auto Dismiss" in les.read_bytes().decode("utf-8","replace") if les.exists() else False) +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_neko3_chrome_dual2.sh", "w") as f: + f.write(FIX) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_fix_neko3_chrome_dual2.sh", + timeout=120, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_neko7_aw_snap.py b/scripts/_fix_neko7_aw_snap.py new file mode 100644 index 0000000..cc789ff --- /dev/null +++ b/scripts/_fix_neko7_aw_snap.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Diagnose + soft-recover neko-7 Aw Snap (Chrome error 9) without wiping login.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-18000:] if len(out) > 18000 else out, flush=True) + return code, out + + +c = ssh() + +# 1) Diagnose +run( + c, + r""" +set +e +echo ===HOST_MEM=== +free -h +swapon --show || true +echo ===NEKO7=== +docker ps -a --filter name=douyinweb-neko-7 --format '{{.Names}} {{.Status}}' +docker inspect douyinweb-neko-7 --format 'State={{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Mem={{.HostConfig.Memory}} MemSwap={{.HostConfig.MemorySwap}}' +echo ===ALL_NEKO_STATS=== +docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}} ({{.MemPerc}})' $(docker ps -q --filter name=douyinweb-neko) 2>/dev/null +echo ===NEKO_STATES=== +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +echo ===CDP=== +docker exec douyinweb-neko-7 python3 -c "import json,urllib.request; tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read().decode()); +[print((t.get('type'), (t.get('url') or '')[:140], (t.get('title') or '')[:50])) for t in tabs]" +echo ===CHROME=== +docker exec douyinweb-neko-7 sh -c "ps aux | grep -i chrome | grep -v grep | head -25" +echo ===OOM=== +dmesg -T 2>/dev/null | grep -iE 'oom|Out of memory|Killed process' | tail -20 +""", +) + +# 2) Soft recover: CDP reload crashed tab / navigate livestreaming again. No Preferences rewrite. +run( + c, + r""" +set +e +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time, urllib.request +from app import youtube_neko as yn + +nid = 7 +print("ensure", yn.ensure_instance_running(nid)) +st = yn._container_state(nid, check_http=True) +print("state", {k: st.get(k) for k in ("running","ready","status","exists")}) + +# CDP: list + reload pages that look crashed / blank, or re-open Studio live for asian group +name = yn._container_name(nid) +py = r''' +import json, urllib.request, time +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read().decode()) +pages=[t for t in tabs if (t.get("type") or "page")=="page"] +print("pages_before", len(pages)) +for t in pages: + print("TAB", (t.get("url") or "")[:160], "|", (t.get("title") or "")[:60]) + +# Prefer existing livestreaming tab +live=[t for t in pages if "studio.youtube.com" in (t.get("url") or "").lower() and "livestreaming" in (t.get("url") or "").lower()] +studio=[t for t in pages if "studio.youtube.com" in (t.get("url") or "").lower()] +pick=(live or studio or pages[:1] or [None])[0] +if not pick: + print("no_tabs") + raise SystemExit(0) +tid=pick.get("id") +ws=pick.get("webSocketDebuggerUrl") +url=pick.get("url") or "" +print("pick", tid, url[:120]) +# Activate + Page.reload via CDP HTTP/websocket-less: use /json/activate then Runtime via python ws minimal +try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=3).read() +except Exception as e: + print("activate_err", e) + +# Soft navigate to same URL (recovers Aw Snap without new profile) +want = url if "livestreaming" in url.lower() else "https://studio.youtube.com/" +# If Aw Snap, Page.navigate via CDP +import base64, os, socket, struct +def ws_connect(u): + assert u.startswith("ws://") + hostport, path = u[5:].split("/",1) + path="/"+path + host,port=hostport.split(":") + sock=socket.create_connection((host,int(port)), timeout=6) + key=base64.b64encode(os.urandom(16)).decode() + req=(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode() + sock.sendall(req) + buf=b"" + while b"\r\n\r\n" not in buf: + buf += sock.recv(4096) + return sock +def ws_send(sock, payload): + data=json.dumps(payload).encode(); mask=os.urandom(4) + header=bytearray([0x81, 0x80|len(data)]); header.extend(mask) + sock.sendall(bytes(header)+bytes(b^mask[i%4] for i,b in enumerate(data))) +def ws_recv(sock): + def readexact(n): + out=b"" + while len(out)/dev/null 2>&1; then ufw allow 52300:52363/tcp >/dev/null 2>&1 || true ufw allow 52300:52363/udp >/dev/null 2>&1 || true + ufw allow 62300:62307/tcp >/dev/null 2>&1 || true + ufw allow 62300:62307/udp >/dev/null 2>&1 || true + ufw allow 62500:62579/udp >/dev/null 2>&1 || true ufw allow 52000:52098/udp >/dev/null 2>&1 || true ufw allow 52101:52199/udp >/dev/null 2>&1 || true ufw allow 52201:52299/udp >/dev/null 2>&1 || true diff --git a/scripts/_fix_nomadro_caddy_next.py b/scripts/_fix_nomadro_caddy_next.py new file mode 100644 index 0000000..ffc2dde --- /dev/null +++ b/scripts/_fix_nomadro_caddy_next.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Fix Caddy: remove duplicate site; apex nomadro.com → Next :4003 only.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +set -e +# remove conflicting import site we created +rm -f /etc/caddy/sites/nomadro.com.caddy +echo 'removed sites/nomadro.com.caddy' + +# backup then point apex at Next :4003 (skip audience router / WP) +cp -a /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.nomadro_next_$(date +%Y%m%d_%H%M%S) +python3 - <<'PY' +from pathlib import Path +p = Path("/etc/caddy/Caddyfile") +text = p.read_text(encoding="utf-8") +old = """# Audience router: zh → Next.js, en/bots → WordPress +nomadro.com { + encode gzip + reverse_proxy 127.0.0.1:4403 +}""" +new = """# Next.js only (WordPress / audience router not used) +nomadro.com { + encode gzip + reverse_proxy 127.0.0.1:4003 +}""" +if old not in text: + # fallback replace port only inside nomadro.com block + import re + text2, n = re.subn( + r"(nomadro\.com\s*\{[^}]*reverse_proxy\s+)127\.0\.0\.1:4403", + r"\g<1>127.0.0.1:4003", + text, + count=1, + flags=re.S, + ) + if n != 1: + raise SystemExit(f"patch failed n={n}") + text = text2 +else: + text = text.replace(old, new, 1) +p.write_text(text, encoding="utf-8") +print("patched Caddyfile") +PY + +head -20 /etc/caddy/Caddyfile +caddy validate --config /etc/caddy/Caddyfile +systemctl reload caddy || systemctl restart caddy +sleep 1 +systemctl is-active caddy nomadro.service +# ensure next is up +systemctl restart nomadro.service +sleep 2 +systemctl is-active nomadro.service +ss -lntp | grep ':4003' || true +curl -sS -m 10 -o /dev/null -w 'local=%{http_code}\n' http://127.0.0.1:4003/ +curl -sS -m 15 -o /dev/null -w 'public=%{http_code}\n' -L https://nomadro.com/ +curl -sS -m 15 -o /dev/null -w 'www=%{http_code}\n' -L https://www.nomadro.com/ +# do not touch wordpress containers +echo 'wp_left_as_is:' +docker ps --format '{{.Names}} {{.Status}}' | grep -i wordpress || true +systemctl is-active nomadro-router.service || echo 'router=inactive (ok)' +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_nomadro_caddy.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_fix_nomadro_caddy.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_fix_nomadro_caddy_next.sh b/scripts/_fix_nomadro_caddy_next.sh new file mode 100644 index 0000000..ea748de --- /dev/null +++ b/scripts/_fix_nomadro_caddy_next.sh @@ -0,0 +1,46 @@ +#!/bin/bash +set -e +rm -f /etc/caddy/sites/nomadro.com.caddy +echo 'removed sites/nomadro.com.caddy' + +cp -a /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.nomadro_next_$(date +%Y%m%d_%H%M%S) + +python3 <<'PY' +from pathlib import Path +import re +p = Path("/etc/caddy/Caddyfile") +text = p.read_text(encoding="utf-8") +text2, n = re.subn( + r"(nomadro\.com\s*\{[^}]*?reverse_proxy\s+)127\.0\.0\.1:4403", + r"\g<1>127.0.0.1:4003", + text, + count=1, + flags=re.S, +) +if n != 1: + raise SystemExit(f"patch failed n={n}") +text2 = text2.replace( + "# Audience router: zh → Next.js, en/bots → WordPress", + "# Next.js only (WordPress / audience router not used)", + 1, +) +p.write_text(text2, encoding="utf-8") +print("patched Caddyfile ok") +PY + +head -20 /etc/caddy/Caddyfile +caddy validate --config /etc/caddy/Caddyfile +systemctl reload caddy || systemctl restart caddy +sleep 1 +systemctl is-active caddy +systemctl enable --now nomadro.service +systemctl restart nomadro.service +sleep 2 +systemctl is-active nomadro.service +ss -lntp | grep ':4003' || true +curl -sS -m 10 -o /dev/null -w 'local=%{http_code}\n' http://127.0.0.1:4003/ +curl -sS -m 15 -o /dev/null -w 'public=%{http_code}\n' -L https://nomadro.com/ +curl -sS -m 15 -o /dev/null -w 'www=%{http_code}\n' -L https://www.nomadro.com/ +echo 'wp_left_as_is:' +docker ps --format '{{.Names}} {{.Status}}' | grep -i wordpress || true +systemctl is-active nomadro-router.service || echo 'router=inactive (ok)' diff --git a/scripts/_fix_ops_and_bounce_assign.py b/scripts/_fix_ops_and_bounce_assign.py new file mode 100644 index 0000000..20970ff --- /dev/null +++ b/scripts/_fix_ops_and_bounce_assign.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Fix dual/orphan chrome on physical ops-neko + verify assign trap file.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +FIX = r"""#!/bin/bash +set -e +echo '=== trap inside neko-3 ===' +docker exec douyinweb-neko-3 grep -n on_supervisor_stop /etc/neko/browser-launch.sh | head +docker exec douyinweb-neko-3 wc -l /etc/neko/browser-launch.sh +wc -l /opt/douyinWEB/backend/neko/browser-launch.sh + +fix_one() { + local N="$1" + echo "===== $N =====" + docker exec "$N" supervisorctl stop google-chrome || true + sleep 1 + docker exec -i "$N" python3 - <<'PY' +import os, signal, time +n=0 +for _ in range(3): + for pid in list(os.listdir("/proc")): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw or b"/opt/google/chrome" in raw: + try: + os.kill(int(pid), signal.SIGKILL); n+=1 + except Exception: + pass + time.sleep(0.4) +print("killed", n) +PY + docker exec "$N" bash -lc 'rm -f /home/neko/.config/google-chrome/SingletonCookie /home/neko/.config/google-chrome/SingletonLock /home/neko/.config/google-chrome/SingletonSocket /home/neko/.config/google-chrome/SingletonStartupLock /home/neko/.config/google-chrome/lockfile /home/neko/.config/google-chrome/DevToolsActivePort 2>/dev/null; true' + docker exec "$N" supervisorctl start google-chrome +} + +for N in douyinweb-ops-neko-1 douyinweb-ops-neko-2; do + docker inspect "$N" >/dev/null 2>&1 && fix_one "$N" +done + +# bounce assign chrome so browser-launch process reloads trap from bind-mount +for i in 1 2 3 4 5 6 7 8; do + N=douyinweb-neko-$i + docker inspect "$N" >/dev/null 2>&1 || continue + fix_one "$N" +done + +echo '===== wait =====' +sleep 22 +for N in douyinweb-ops-neko-1 douyinweb-ops-neko-2 \ + douyinweb-neko-1 douyinweb-neko-2 douyinweb-neko-3 douyinweb-neko-4 \ + douyinweb-neko-5 douyinweb-neko-6 douyinweb-neko-7 douyinweb-neko-8; do + docker inspect "$N" >/dev/null 2>&1 || continue + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1; trap=False +try: + trap=b"on_supervisor_stop" in open("/etc/neko/browser-launch.sh","rb").read() +except Exception as e: + trap=str(e) +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw} trap={trap}") +PY +) + echo "$N $out" +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_ops_and_bounce_assign.sh", "w") as f: + f.write(FIX) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_fix_ops_and_bounce_assign.sh", + timeout=420, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_chrome_env.py b/scripts/_fix_opsneko_chrome_env.py new file mode 100644 index 0000000..ee0d69f --- /dev/null +++ b/scripts/_fix_opsneko_chrome_env.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Recreate ops-neko with full assign-parity env so Chrome actually starts. + +ops compose on physical is still the old stub (no ENV_USER / managed policies). +Supervisor google-chrome.conf needs ENV_USER + ENV_DISPLAY or Chrome never launches → black screen. +""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +ROOT = "/opt/douyinWEB" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*PHYS[:3], password=PHYS[3], timeout=45, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=180): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +# Upload patch files then run recreate via python on host +REMOTE_FIX = r''' +import os, shutil, subprocess +from pathlib import Path + +os.chdir("/opt/douyinWEB/backend") +sys_path_insert = "/opt/douyinWEB/backend" +import sys +sys.path.insert(0, sys_path_insert) + +# Prefer in-tree modules if already updated; else rewrite compose from assign template. +from app import youtube_neko as yn +from app import ops_neko + +# Force rewrite compose with shared compose_service_lines +text = ops_neko._render_compose(max(ops_neko.ops_neko_db.max_slot(), 1)) +path = ops_neko._compose_path() +path.write_text(text, encoding="utf-8") +print("compose_head:") +print("\n".join(text.splitlines()[:45])) + +# Recreate all ops containers, keep running set +max_slot = max(ops_neko.ops_neko_db.max_slot(), 1) +was = {i for i in range(1, max_slot+1) if ops_neko._container_running(i)} +# Always ensure slot 1 comes up for operator +was.add(1) +print("resume", sorted(was)) +r = ops_neko.sync_compose(start_slots=was, force_recreate=True) +print("sync", r) +''' + + +def main(): + c = ssh() + # First: check if local code has compose_service_lines; if not, scp files + has = run( + c, + "echo '4669805' | sudo -S -p '' grep -c compose_service_lines " + f"{ROOT}/backend/app/youtube_neko.py || true", + ).strip() + print("has_compose_service_lines:", has, flush=True) + + # Upload current local modules + from pathlib import Path + + local = Path(__file__).resolve().parents[1] + sftp = c.open_sftp() + for rel in ( + "backend/app/youtube_neko.py", + "backend/app/ops_neko.py", + "backend/app/ops_neko_db.py", + ): + src = local / rel + dst = f"/tmp/_up_{Path(rel).name}" + with sftp.file(dst, "wb") as f: + f.write(src.read_bytes()) + print("uploaded", rel, flush=True) + sftp.close() + + print( + run( + c, + "echo '4669805' | sudo -S -p '' bash -lc '" + f"install -m 644 /tmp/_up_youtube_neko.py {ROOT}/backend/app/youtube_neko.py; " + f"install -m 644 /tmp/_up_ops_neko.py {ROOT}/backend/app/ops_neko.py; " + f"install -m 644 /tmp/_up_ops_neko_db.py {ROOT}/backend/app/ops_neko_db.py; " + "sed -i \"s/\\r$//\" " + f"{ROOT}/backend/app/youtube_neko.py {ROOT}/backend/app/ops_neko.py {ROOT}/backend/app/ops_neko_db.py; " + # recreate via python + f"cd {ROOT}/backend && ./../.venv/bin/python - <<\"PY\"\n" + "import sys\n" + "sys.path.insert(0, \".\")\n" + "from app import ops_neko\n" + "from app import ops_neko_db\n" + "max_slot = max(ops_neko_db.max_slot(), 1)\n" + "text = ops_neko._render_compose(max_slot)\n" + "ops_neko._compose_path().write_text(text, encoding=\"utf-8\")\n" + "print(\"ENV_USER in compose\", \"ENV_USER\" in text)\n" + "print(\"LIVE_OPS in compose\", \"NEKO_LIVE_OPS_EXTENSION\" in text)\n" + "print(\"\\n\".join(text.splitlines()[:55]))\n" + "was = {i for i in range(1, max_slot+1) if ops_neko._container_running(i)}\n" + "was.add(1)\n" + "print(\"resume\", sorted(was))\n" + "print(ops_neko.sync_compose(start_slots=was, force_recreate=True))\n" + "PY\n" + "'", + 300, + ), + flush=True, + ) + + time.sleep(8) + print( + run( + c, + "echo '4669805' | sudo -S -p '' bash -lc '" + "docker exec douyinweb-ops-neko-1 env | grep -E \"ENV_USER|ENV_DISPLAY|NEKO_LIVE|NEKO_MANAGED|NEKO_TAMPER|HOME|USER=\" | sort; " + "echo ---chrome-log---; " + "docker exec douyinweb-ops-neko-1 bash -lc \"tail -40 /var/log/neko/google-chrome.log 2>/dev/null || true\"; " + "echo ---procs---; " + "docker exec douyinweb-ops-neko-1 bash -lc \"command -v ps; ls /proc | head; pgrep -a chrome | head -10; pgrep -a Xvfb; pgrep -a openbox\"; " + "echo ---supervisorctl---; " + "docker exec douyinweb-ops-neko-1 bash -lc \"supervisorctl status 2>/dev/null || true\"; " + "'", + 60, + ), + flush=True, + ) + c.close() + print("DONE — reopen https://dy.nomadro.com/ops-neko/1/", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_nat_bind.py b/scripts/_fix_opsneko_nat_bind.py new file mode 100644 index 0000000..135d4dc --- /dev/null +++ b/scripts/_fix_opsneko_nat_bind.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Force ops-neko NAT1TO1=Tencent + 0.0.0.0 HTTP bind, then recreate.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +ROOT = "/opt/douyinWEB" +LOCAL = Path(__file__).resolve().parents[1] +CN_IP = "82.157.112.245" +VPS_IP = "107.173.30.245" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*PHYS[:3], password=PHYS[3], timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_up_ops_neko.py", "wb") as f: + f.write((LOCAL / "backend/app/ops_neko.py").read_bytes()) + sftp.close() + + cmd = f""" +echo '4669805' | sudo -S -p '' bash -lc ' +set -e +install -m 644 /tmp/_up_ops_neko.py {ROOT}/backend/app/ops_neko.py +sed -i "s/\\r$//" {ROOT}/backend/app/ops_neko.py + +# Ensure CN ICE preferred + VPS fallback env on API unit (idempotent) +SVC=/etc/systemd/system/douyinweb-api.service +grep -q DY_NEKO_CN_NAT1TO1= "$SVC" || sed -i "/DY_NEKO_NAT1TO1=/a Environment=DY_NEKO_CN_NAT1TO1={CN_IP}" "$SVC" +grep -q DY_NEKO_VPS_NAT1TO1= "$SVC" || sed -i "/DY_NEKO_NAT1TO1=/a Environment=DY_NEKO_VPS_NAT1TO1={VPS_IP}" "$SVC" +# Keep legacy NAT1TO1 as CN (primary) for older code paths +sed -i "s|Environment=DY_NEKO_NAT1TO1=.*|Environment=DY_NEKO_NAT1TO1={CN_IP}|" "$SVC" +systemctl daemon-reload +# do NOT restart API now — just export for this recreate +export DY_NEKO_CN_NAT1TO1={CN_IP} +export DY_NEKO_VPS_NAT1TO1={VPS_IP} +export DY_NEKO_NAT1TO1={CN_IP} +export DY_NEKO_HTTP_BIND=0.0.0.0 +export DY_NEKO_EDGE_UPSTREAM=10.8.0.2 + +cd {ROOT}/backend +PY=../.venv/bin/python +$PY - </dev/null | head -1); " + "echo PY=$PY; " + "$PY /tmp/_fix_ops_nat.py; " + "sleep 8; " + "docker exec douyinweb-ops-neko-1 env | grep -E \"NAT1TO1|ENV_USER\" | sort; " + "docker port douyinweb-ops-neko-1; " + "docker exec douyinweb-ops-neko-1 supervisorctl status; " + "curl -sS -m 5 -o /dev/null -w \"local=%{http_code}\\n\" http://127.0.0.1:18200/; " + "ss -lntp | grep 18200" + "'", + timeout=360, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_tm_inplace.py b/scripts/_fix_opsneko_tm_inplace.py new file mode 100644 index 0000000..30b02bc --- /dev/null +++ b/scripts/_fix_opsneko_tm_inplace.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""In-place overwrite bind-mounted browser-launch.sh so containers see TM --load-extension.""" +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +REMOTE_SH = r""" +set -e +BL=/opt/douyinWEB/backend/neko/browser-launch.sh +# in-place overwrite (same inode) so docker bind mounts refresh +cat /tmp/browser-launch.sh.tmfix > "$BL" +chmod 755 "$BL" +# policies + seed prefs + manifest in-place too +cat /tmp/policies.json.tmfix > /opt/douyinWEB/backend/neko/policies/policies.json +chmod 644 /opt/douyinWEB/backend/neko/policies/policies.json +cat /tmp/Preferences.tmfix > /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Preferences +chmod 644 /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Preferences +MF=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json +if [ -f "$MF" ]; then + cat /tmp/tm_manifest.json.tmfix > "$MF" + chmod 644 "$MF" +fi + +echo "--- host inode check ---" +grep -n "Offline Tampermonkey\|tm_load_dir" "$BL" | head -5 +docker exec douyinweb-ops-neko-1 grep -n "Offline Tampermonkey\|tm_load_dir" /etc/neko/browser-launch.sh | head -5 || true + +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== RESTART $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, shutil +from pathlib import Path +EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE=Path("/home/neko/.config/google-chrome/Default") +SEED_EXT=Path("/etc/neko/tampermonkey-seed/Default/Extensions")/EXT +SEED_PREF=Path("/etc/neko/tampermonkey-seed/Default/Preferences") + +def load(p): + try: return json.loads(p.read_text(encoding="utf-8")) + except Exception: return {} + +for p in (BASE/"Extensions"/EXT, BASE/"Managed Extension Settings"/EXT): + if p.exists(): + shutil.rmtree(p, ignore_errors=True) +(BASE/"Extensions").mkdir(parents=True, exist_ok=True) +shutil.copytree(SEED_EXT, BASE/"Extensions"/EXT) +mf=BASE/"Extensions"/EXT/"5.5.0_0"/"manifest.json" +if mf.exists(): + d=load(mf); d.pop("update_url", None) + mf.write_text(json.dumps(d, ensure_ascii=False, indent=3)+"\n", encoding="utf-8") +seed=((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) or {} +entry=dict(seed) +entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False}) +entry.pop("disable_reasons", None) +mf2=entry.get("manifest") +if isinstance(mf2, dict): + mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2 +# NEVER rewrite Secure Preferences — nukes Google login. +pref=BASE/"Preferences" +d=load(pref) if pref.exists() else {} +d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry) +d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True +pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8") +print("profile_ready") +PY + docker exec "$name" bash -lc 'chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences "/home/neko/.config/google-chrome/Default/Secure Preferences" 2>/dev/null || true' + docker exec "$name" supervisorctl restart google-chrome +done + +sleep 28 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== PROBE $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, os, re, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +e=((json.loads(Path("/home/neko/.config/google-chrome/Default/Preferences").read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore"), "disable", e.get("disable_reasons")) +pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) +print("forcelist", pol.get("ExtensionInstallForcelist")) +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: + cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00", b" ").decode("utf-8","replace") + except Exception: + continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_extension", m.group(1) if m else None) + found=True + break +if not found: + print("load_extension NOT_FOUND") +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw)) +for t in sw: print(" ", t.get("url")) +print("tm_pages", sum(1 for t in tabs if "chrome-extension://dhdgff" in (t.get("url") or ""))) +# also check live-ops loaded +lo=[t for t in tabs if t.get("type")=="service_worker" and "live-ops" in (t.get("url") or "")] +print("live_ops_sw", len(lo)) +PY +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + uploads = { + "/tmp/browser-launch.sh.tmfix": ROOT / "backend/neko/browser-launch.sh", + "/tmp/policies.json.tmfix": ROOT / "backend/neko/policies/policies.json", + "/tmp/Preferences.tmfix": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences", + "/tmp/tm_manifest.json.tmfix": ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json", + } + for remote, local in uploads.items(): + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + print("uploaded", local.name) + with sftp.file("/tmp/_tm_inplace.sh", "wb") as f: + f.write(REMOTE_SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_tm_inplace.sh", timeout=360) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_tm_loadext.py b/scripts/_fix_opsneko_tm_loadext.py new file mode 100644 index 0000000..9879576 --- /dev/null +++ b/scripts/_fix_opsneko_tm_loadext.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +REMOTE_SH = r""" +set -e +install -m 755 /tmp/browser-launch.sh.tmfix /opt/douyinWEB/backend/neko/browser-launch.sh +for p in \ + /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json \ + /etc/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json +do + if [ -f "$p" ]; then + install -m 644 /tmp/tm_manifest.json.tmfix "$p" || true + echo updated "$p" + fi +done + +# push browser-launch into each container if the path is writable +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== RESTART $name =====" + docker exec -i "$name" tee /tmp/browser-launch.sh.new < /opt/douyinWEB/backend/neko/browser-launch.sh >/dev/null + docker exec "$name" bash -lc ' + for t in /etc/neko/browser-launch.sh /usr/local/bin/browser-launch.sh /opt/neko/browser-launch.sh; do + if [ -f "$t" ] && [ -w "$t" ]; then + cp /tmp/browser-launch.sh.new "$t" + chmod +x "$t" + echo copied_to "$t" + fi + done + # also find how chrome is started + supervisorctl status google-chrome || true + grep -R "browser-launch" /etc/supervisor /etc/neko 2>/dev/null | head -20 || true + ' + docker exec "$name" supervisorctl restart google-chrome || docker exec "$name" supervisorctl start google-chrome +done + +sleep 28 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== PROBE $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, os, re, urllib.request +from pathlib import Path +ext = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +pref = Path("/home/neko/.config/google-chrome/Default/Preferences") +e = ((json.loads(pref.read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore"), "disable", e.get("disable_reasons")) +found = False +for pid in os.listdir("/proc"): + if not pid.isdigit(): + continue + try: + cmd = open(f"/proc/{pid}/cmdline", "rb").read().replace(b"\x00", b" ").decode("utf-8", "replace") + except Exception: + continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m = re.search(r"--load-extension=([^ ]+)", cmd) + print("load_extension", m.group(1) if m else None) + found = True + break +if not found: + print("load_extension", "NOT_FOUND") +try: + tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as ex: + print("cdp_err", ex) + tabs = [] +sw = [t for t in tabs if t.get("type") == "service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw)) +for t in sw: + print(" ", t.get("url")) +print("tm_pages", len([t for t in tabs if "chrome-extension://dhdgff" in (t.get("url") or "")])) +PY +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/browser-launch.sh.tmfix", "wb") as f: + f.write((ROOT / "backend/neko/browser-launch.sh").read_bytes()) + with sftp.file("/tmp/tm_manifest.json.tmfix", "wb") as f: + f.write( + ( + ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" + ).read_bytes() + ) + with sftp.file("/tmp/_tm_loadext.sh", "wb") as f: + f.write(REMOTE_SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_tm_loadext.sh", timeout=360) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_tm_offline.py b/scripts/_fix_opsneko_tm_offline.py new file mode 100644 index 0000000..89d45b5 --- /dev/null +++ b/scripts/_fix_opsneko_tm_offline.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Offline Tampermonkey fix for ops-neko: drop Google forcelist, reseed unpacked TM.""" +import base64 +import json +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +POL = ROOT / "backend/neko/policies/policies.json" +SEED_PREF = ROOT / "backend/neko/tampermonkey-seed/Default/Preferences" + +INSIDE = r''' +import json, shutil +from pathlib import Path + +EXT = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE = Path("/home/neko/.config/google-chrome/Default") +SEED_EXT = Path("/etc/neko/tampermonkey-seed/Default/Extensions") / EXT +SEED_PREF = Path("/etc/neko/tampermonkey-seed/Default/Preferences") + +def load(p): + try: + return json.loads(p.read_text(encoding="utf-8")) + except Exception: + return {} + +# wipe extension + storage so Chrome does not keep policy-broken state +for p in ( + BASE / "Extensions" / EXT, + BASE / "Local Extension Settings" / EXT, + BASE / "Managed Extension Settings" / EXT, +): + if p.exists(): + shutil.rmtree(p, ignore_errors=True) + print("removed", p) + +(BASE / "Extensions").mkdir(parents=True, exist_ok=True) +if not SEED_EXT.exists(): + raise SystemExit("NO_SEED_EXT") +shutil.copytree(SEED_EXT, BASE / "Extensions" / EXT) +print("copied_ext") + +seed_entry = ((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) +if not isinstance(seed_entry, dict): + raise SystemExit("NO_SEED_PREF_ENTRY") + +# Unpacked offline install — do NOT claim webstore / EXTERNAL_POLICY (7) +entry = dict(seed_entry) +entry["state"] = 1 +entry["path"] = f"{EXT}/5.5.0_0" +entry["location"] = 4 # UNPACKED +entry["from_webstore"] = False +entry.pop("disable_reasons", None) +entry.pop("blacklist", None) + +# NEVER rewrite Secure Preferences — Chrome MAC/signing; nukes Google login. +pref = BASE / "Preferences" +d = load(pref) if pref.exists() else {} +settings = d.setdefault("extensions", {}).setdefault("settings", {}) +settings[EXT] = dict(entry) +d.setdefault("extensions", {}).setdefault("ui", {})["developer_mode"] = True +pref.write_text(json.dumps(d, separators=(",", ":")), encoding="utf-8") +print("patched Preferences loc", settings[EXT].get("location"), "webstore", settings[EXT].get("from_webstore")) + +print("policy_forcelist_check") +try: + pol = json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) + print("forcelist", pol.get("ExtensionInstallForcelist")) +except Exception as e: + print("pol_err", e) +''' + +B64 = base64.b64encode(INSIDE.encode()).decode() + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/policies_tm_offline.json", "wb") as f: + f.write(POL.read_bytes()) + sftp.close() + + remote = """ +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +install -m 644 /tmp/policies_tm_offline.json /opt/douyinWEB/backend/neko/policies/policies.json +sed -i "s/\\r$//" /opt/douyinWEB/backend/neko/policies/policies.json +B64="__B64__" +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + docker exec $name supervisorctl stop google-chrome || true + sleep 2 + printf %s "$B64" | docker exec -i $name bash -lc "base64 -d > /tmp/_tm_offline_fix.py && python3 /tmp/_tm_offline_fix.py" + docker exec $name bash -lc "chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences /home/neko/.config/google-chrome/Default/Secure\\ Preferences 2>/dev/null || true" + docker exec $name supervisorctl start google-chrome +done +sleep 18 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== VERIFY $name =====" + docker exec $name python3 - <<'"'"'PY'"'"' +import json +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +p=Path("/home/neko/.config/google-chrome/Default/Preferences") +d=json.loads(p.read_text()) +e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore"), "path", e.get("path"), "disable", e.get("disable_reasons")) +pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) +print("forcelist", pol.get("ExtensionInstallForcelist")) +import urllib.request +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_service_workers", len(sw)) +for t in sw: + print(" SW", t.get("url")) +ext_pages=[t for t in tabs if "chrome-extension://dhdgff" in (t.get("url") or "")] +print("tm_pages", [(t.get("title"), (t.get("url") or "")[:80]) for t in ext_pages[:5]]) +PY + docker exec $name supervisorctl status google-chrome +done +' +""".replace("__B64__", B64) + _i, o, e = c.exec_command(remote, timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_tm_offline2.py b/scripts/_fix_opsneko_tm_offline2.py new file mode 100644 index 0000000..a60c284 --- /dev/null +++ b/scripts/_fix_opsneko_tm_offline2.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Re-apply offline TM + deploy updated policies/seed/browser-launch to physical ops-neko.""" +import base64 +import json +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +FILES = { + "/opt/douyinWEB/backend/neko/policies/policies.json": ROOT / "backend/neko/policies/policies.json", + "/opt/douyinWEB/backend/neko/browser-launch.sh": ROOT / "backend/neko/browser-launch.sh", + "/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Preferences": ROOT + / "backend/neko/tampermonkey-seed/Default/Preferences", +} + +INSIDE = r''' +import json, shutil +from pathlib import Path +EXT = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE = Path("/home/neko/.config/google-chrome/Default") +SEED_EXT = Path("/etc/neko/tampermonkey-seed/Default/Extensions") / EXT +SEED_PREF = Path("/etc/neko/tampermonkey-seed/Default/Preferences") + +def load(p): + try: + return json.loads(p.read_text(encoding="utf-8")) + except Exception: + return {} + +for p in ( + BASE / "Extensions" / EXT, + BASE / "Local Extension Settings" / EXT, + BASE / "Managed Extension Settings" / EXT, +): + if p.exists(): + shutil.rmtree(p, ignore_errors=True) + print("removed", str(p)) + +(BASE / "Extensions").mkdir(parents=True, exist_ok=True) +shutil.copytree(SEED_EXT, BASE / "Extensions" / EXT) +print("copied_ext") +mf_path = BASE / "Extensions" / EXT / "5.5.0_0" / "manifest.json" +if mf_path.exists(): + md = load(mf_path) + if "update_url" in md: + md.pop("update_url") + mf_path.write_text(json.dumps(md, ensure_ascii=False, indent=3) + "\n", encoding="utf-8") + print("stripped_seed_manifest_update_url") + +seed_entry = ((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) +if not isinstance(seed_entry, dict): + raise SystemExit("NO_SEED_PREF") +entry = dict(seed_entry) +entry["state"] = 1 +entry["path"] = f"{EXT}/5.5.0_0" +entry["location"] = 4 +entry["from_webstore"] = False +entry.pop("disable_reasons", None) +mf = entry.get("manifest") +if isinstance(mf, dict): + mf = dict(mf) + mf.pop("update_url", None) + entry["manifest"] = mf + +# NEVER rewrite Secure Preferences — Chrome MAC; overwriting logs out Google. +pref = BASE / "Preferences" +d = load(pref) if pref.exists() else {} +settings = d.setdefault("extensions", {}).setdefault("settings", {}) +settings[EXT] = dict(entry) +d.setdefault("extensions", {}).setdefault("ui", {})["developer_mode"] = True +pref.write_text(json.dumps(d, separators=(",", ":")), encoding="utf-8") +print("patched Preferences", settings[EXT].get("location"), settings[EXT].get("from_webstore")) + +pol = load(Path("/etc/opt/chrome/policies/managed/policies.json")) +print("forcelist", pol.get("ExtensionInstallForcelist")) +''' + +PROBE = r''' +import json, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +p=Path("/home/neko/.config/google-chrome/Default/Preferences") +d=json.loads(p.read_text()) +e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore")) +print("path", e.get("path"), "disable", e.get("disable_reasons")) +mf=e.get("manifest") or {} +print("update_url", mf.get("update_url")) +pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) +print("forcelist", pol.get("ExtensionInstallForcelist")) +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as ex: + print("cdp_err", type(ex).__name__, ex) + tabs=[] +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw)) +for t in sw: + print(" ", t.get("url")) +# open extensions page briefly via CDP new tab? just list chrome-extension pages +pages=[t for t in tabs if "chrome-extension://dhdgff" in (t.get("url") or "")] +print("tm_pages", len(pages)) +for t in pages[:6]: + print(" ", t.get("title"), (t.get("url") or "")[:100]) +''' + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for remote, local in FILES.items(): + tmp = f"/tmp/{Path(remote).name}.tmfix" + with sftp.file(tmp, "wb") as f: + f.write(local.read_bytes()) + print("uploaded", remote) + # also write probe/inside scripts + with sftp.file("/tmp/_tm_offline_inside.py", "wb") as f: + f.write(INSIDE.encode()) + with sftp.file("/tmp/_tm_offline_probe.py", "wb") as f: + f.write(PROBE.encode()) + + remote_sh = r""" +set -e +install -m 644 /tmp/policies.json.tmfix /opt/douyinWEB/backend/neko/policies/policies.json +install -m 755 /tmp/browser-launch.sh.tmfix /opt/douyinWEB/backend/neko/browser-launch.sh +install -m 644 /tmp/Preferences.tmfix /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Preferences +if [ -d /etc/neko/tampermonkey-seed/Default ]; then + install -m 644 /tmp/Preferences.tmfix /etc/neko/tampermonkey-seed/Default/Preferences || true +fi +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== FIX $name =====" + docker exec $name supervisorctl stop google-chrome || true + sleep 2 + docker exec -i $name tee /tmp/_tm_offline_inside.py < /tmp/_tm_offline_inside.py >/dev/null + docker exec $name python3 /tmp/_tm_offline_inside.py + docker exec $name bash -lc 'chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences "/home/neko/.config/google-chrome/Default/Secure Preferences" 2>/dev/null || true' + docker exec $name supervisorctl start google-chrome +done +sleep 20 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== PROBE $name =====" + docker exec -i $name tee /tmp/_tm_offline_probe.py < /tmp/_tm_offline_probe.py >/dev/null + docker exec $name python3 /tmp/_tm_offline_probe.py + docker exec $name supervisorctl status google-chrome +done +""" + with sftp.file("/tmp/_tm_offline_remote.sh", "wb") as f: + f.write(remote_sh.encode()) + sftp.close() + + _i, o, e = c.exec_command( + "echo 4669805 | sudo -S -p '' bash /tmp/_tm_offline_remote.sh", + timeout=360, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_tm_remount.py b/scripts/_fix_opsneko_tm_remount.py new file mode 100644 index 0000000..a783429 --- /dev/null +++ b/scripts/_fix_opsneko_tm_remount.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +REMOTE_SH = r""" +set -e +BL=/opt/douyinWEB/backend/neko/browser-launch.sh +# ensure current host content +cat /tmp/browser-launch.sh.tmfix > "$BL" +chmod 755 "$BL" +cat /tmp/policies.json.tmfix > /opt/douyinWEB/backend/neko/policies/policies.json +cat /tmp/Preferences.tmfix > /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Preferences +MF=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json +[ -f "$MF" ] && cat /tmp/tm_manifest.json.tmfix > "$MF" + +HOST_MD5=$(md5sum "$BL" | awk '{print $1}') +echo "host_md5 $HOST_MD5" + +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== REMOUNT $name =====" + docker stop "$name" + docker start "$name" + sleep 3 + CTR_MD5=$(docker exec "$name" md5sum /etc/neko/browser-launch.sh | awk '{print $1}') + echo "ctr_md5 $CTR_MD5" + docker exec "$name" grep -n "Offline Tampermonkey\|tm_load_dir" /etc/neko/browser-launch.sh | head -5 || echo "MISSING_TM_BLOCK" +done + +# wait for chrome up +sleep 15 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== WAIT chrome $name =====" + for n in $(seq 1 30); do + if docker exec "$name" supervisorctl status google-chrome 2>/dev/null | grep -q RUNNING; then + break + fi + sleep 2 + done + docker exec "$name" supervisorctl status google-chrome || true +done + +sleep 12 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== PROBE $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, os, re, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +pref=Path("/home/neko/.config/google-chrome/Default/Preferences") +e={} +if pref.exists(): + e=((json.loads(pref.read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "loc", e.get("location"), "webstore", e.get("from_webstore"), "disable", e.get("disable_reasons")) +pol=json.loads(Path("/etc/opt/chrome/policies/managed/policies.json").read_text()) +print("forcelist", pol.get("ExtensionInstallForcelist")) +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: + cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00", b" ").decode("utf-8","replace") + except Exception: + continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_extension", m.group(1) if m else None) + found=True + break +if not found: + print("load_extension NOT_FOUND") +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as ex: + print("cdp_err", ex); tabs=[] +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw)) +for t in sw: print(" ", t.get("url")) +print("tm_pages", sum(1 for t in tabs if "chrome-extension://dhdgff" in (t.get("url") or ""))) +print("live_ops_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "live-ops" in (t.get("url") or ""))) +PY +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for remote, local in { + "/tmp/browser-launch.sh.tmfix": ROOT / "backend/neko/browser-launch.sh", + "/tmp/policies.json.tmfix": ROOT / "backend/neko/policies/policies.json", + "/tmp/Preferences.tmfix": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences", + "/tmp/tm_manifest.json.tmfix": ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json", + }.items(): + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + with sftp.file("/tmp/_tm_remount.sh", "wb") as f: + f.write(REMOTE_SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_tm_remount.sh", timeout=420) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_opsneko_webrtc_cn.py b/scripts/_fix_opsneko_webrtc_cn.py new file mode 100644 index 0000000..b7126f6 --- /dev/null +++ b/scripts/_fix_opsneko_webrtc_cn.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Fix ops-neko stuck loading: Tencent DNAT + nginx /ops-neko → physical. + +Root cause: + NAT1TO1=82.157.112.245 but Tencent only DNATs assign mux 52300+. + Ops fleet uses 62300+ / EPR 62500+ — ICE never reaches guest → forever loading. + .cn also had no /ops-neko locations (fell through to Next → login/308). +""" +from __future__ import annotations + +import re +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +TENCENT = ("82.157.112.245", 22, "ubuntu", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +NGINX_CONF = "/www/server/panel/vhost/nginx/dy.nomadro.cn.conf" +UP = "10.9.0.2" +OPS_SLOTS = 8 + + +def ssh(spec): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*spec[:3], password=spec[3], timeout=45, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +OPS_DNAT = r'''#!/bin/bash +set -u +COMMENT=OPS-NEKO-WEBRTC +TARGET=10.9.0.2 +WG_IF=wg-dy-cn +PUB_IF=$(ip route get 1.1.1.1 | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}') +echo "[ops-neko-dnat] TARGET=$TARGET PUB=$PUB_IF" + +# wipe previous OPS-NEKO-WEBRTC only (keep assign NEKO-WEBRTC) +while iptables-save -t nat 2>/dev/null | grep -q "$COMMENT"; do + line=$(iptables-save -t nat | grep "$COMMENT" | head -1 | sed 's/^-A /-D /') + iptables -t nat $line || break +done +while iptables-save 2>/dev/null | grep -q "$COMMENT"; do + line=$(iptables-save | grep "$COMMENT" | head -1 | sed 's/^-A /-D /') + iptables $line || break +done + +add() { iptables "$@" || echo "FAIL: $*"; } + +# mux for ops slots 1..8 → 62300..62307 +add -t nat -A PREROUTING -i "$PUB_IF" -p tcp --dport 62300:62307 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" +add -t nat -A PREROUTING -i "$PUB_IF" -p udp --dport 62300:62307 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" +# EPR UDP 62500-62579 (8 * 10) +add -t nat -A PREROUTING -i "$PUB_IF" -p udp --dport 62500:62579 -m comment --comment "$COMMENT" -j DNAT --to-destination "$TARGET" + +# reuse FORWARD/MASQ if NEKO-WEBRTC already has them; still add tagged ones for clarity +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p tcp --dport 62300:62307 -m comment --comment "$COMMENT" -j MASQUERADE 2>/dev/null || true +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p udp --dport 62300:62307 -m comment --comment "$COMMENT" -j MASQUERADE 2>/dev/null || true +add -t nat -A POSTROUTING -o "$WG_IF" -d "$TARGET" -p udp --dport 62500:62579 -m comment --comment "$COMMENT" -j MASQUERADE 2>/dev/null || true + +if command -v ufw >/dev/null 2>&1; then + ufw allow 62300:62307/tcp >/dev/null 2>&1 || true + ufw allow 62300:62307/udp >/dev/null 2>&1 || true + ufw allow 62500:62579/udp >/dev/null 2>&1 || true +fi + +# persist if netfilter-persistent / iptables-save available +if command -v netfilter-persistent >/dev/null 2>&1; then + netfilter-persistent save 2>/dev/null || true +elif [ -d /etc/iptables ]; then + iptables-save > /etc/iptables/rules.v4 2>/dev/null || true +fi + +echo "[ops-neko-dnat] rules:" +iptables -t nat -S | grep "$COMMENT" +''' + + +def nginx_ops_blocks() -> str: + parts = [ + "\n # Ops-Neko tab fleet (douyinweb-ops-neko-*) — same WS headers as /neko/\n", + " location ~ ^/ops-neko/([0-9]+)$ {\n", + " return 308 /ops-neko/$1/;\n", + " }\n", + ] + for n in range(1, OPS_SLOTS + 1): + port = 18200 + n - 1 + parts.append( + f" location /ops-neko/{n}/ {{\n" + f" proxy_pass http://{UP}:{port}/;\n" + f" proxy_http_version 1.1;\n" + f" proxy_set_header Upgrade $http_upgrade;\n" + f" proxy_set_header Connection $connection_upgrade;\n" + f" proxy_set_header Host $host;\n" + f" proxy_set_header X-Forwarded-Host $host;\n" + f" proxy_set_header X-Real-IP $remote_addr;\n" + f" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" + f" proxy_set_header X-Forwarded-Proto $scheme;\n" + f" proxy_read_timeout 3600s;\n" + f" proxy_send_timeout 3600s;\n" + f" proxy_buffering off;\n" + f" }}\n" + ) + return "".join(parts) + + +def main(): + t = ssh(TENCENT) + print("=== 1) DNAT ops-neko WebRTC on Tencent ===", flush=True) + sftp = t.open_sftp() + with sftp.file("/tmp/ops-neko-webrtc-dnat.sh", "w") as f: + f.write(OPS_DNAT) + sftp.close() + print( + run( + t, + "sudo chmod +x /tmp/ops-neko-webrtc-dnat.sh; " + "sudo bash /tmp/ops-neko-webrtc-dnat.sh; " + "sudo install -m 755 /tmp/ops-neko-webrtc-dnat.sh /usr/local/sbin/ops-neko-webrtc-dnat.sh", + 60, + ), + flush=True, + ) + + print("=== 2) nginx /ops-neko locations ===", flush=True) + conf = run(t, f"sudo cat {NGINX_CONF}") + if "location /ops-neko/1/" in conf: + print("ops-neko locations already present — skip insert", flush=True) + else: + blocks = nginx_ops_blocks() + # insert before first /neko/ location block + m = re.search(r"\n\s*# Neko 1\.\.|^\s*location ~ \^/neko/", conf, re.M) + if not m: + m = re.search(r"\n\s*location /neko/1/ \{", conf) + if not m: + raise SystemExit("cannot find insertion point for ops-neko in nginx conf") + new_conf = conf[: m.start()] + "\n" + blocks + conf[m.start() :] + bak = f"{NGINX_CONF}.bak.opsneko.{int(time.time())}" + run(t, f"sudo cp -a {NGINX_CONF} {bak}") + sftp = t.open_sftp() + with sftp.file("/tmp/dy.nomadro.cn.conf.new", "w") as f: + f.write(new_conf) + sftp.close() + out = run( + t, + f"sudo mv /tmp/dy.nomadro.cn.conf.new {NGINX_CONF}; " + f"sudo nginx -t 2>&1; " + f"sudo nginx -s reload 2>&1; " + f"echo bak={bak}", + 60, + ) + print(out, flush=True) + if "syntax is ok" not in out and "test is successful" not in out: + print("nginx -t failed — restoring", flush=True) + print(run(t, f"sudo cp -a {bak} {NGINX_CONF}; sudo nginx -s reload"), flush=True) + raise SystemExit("nginx restore") + + print("=== 3) physical firewall for ops mux via wg-dy-cn ===", flush=True) + p = ssh(PHYS) + print( + run( + p, + "echo '4669805' | sudo -S -p '' bash -lc '" + "ufw allow in on wg-dy-cn to any port 62300:62307 proto tcp 2>/dev/null || true; " + "ufw allow in on wg-dy-cn to any port 62300:62307 proto udp 2>/dev/null || true; " + "ufw allow in on wg-dy-cn to any port 62500:62579 proto udp 2>/dev/null || true; " + "ufw allow in on wg-dy-cn to any port 18200:18207 proto tcp 2>/dev/null || true; " + "iptables -C INPUT -i wg-dy-cn -p tcp --dport 62300:62307 -j ACCEPT 2>/dev/null || " + " iptables -I INPUT -i wg-dy-cn -p tcp --dport 62300:62307 -j ACCEPT; " + "iptables -C INPUT -i wg-dy-cn -p udp --dport 62300:62307 -j ACCEPT 2>/dev/null || " + " iptables -I INPUT -i wg-dy-cn -p udp --dport 62300:62307 -j ACCEPT; " + "iptables -C INPUT -i wg-dy-cn -p udp --dport 62500:62579 -j ACCEPT 2>/dev/null || " + " iptables -I INPUT -i wg-dy-cn -p udp --dport 62500:62579 -j ACCEPT; " + "iptables -C INPUT -i wg-dy-cn -p tcp --dport 18200:18207 -j ACCEPT 2>/dev/null || " + " iptables -I INPUT -i wg-dy-cn -p tcp --dport 18200:18207 -j ACCEPT; " + "echo phys_fw_ok; " + "ss -lntup | grep 62300 | head -3; " + "curl -sS -m 5 -o /dev/null -w \"ops1=%{http_code}\\n\" http://127.0.0.1:18200/; " + "'", + 60, + ), + flush=True, + ) + p.close() + + print("=== 4) verify ===", flush=True) + print( + run( + t, + r""" +curl -sS -m 12 -o /dev/null -w 'cn_ops1=%{http_code}\n' https://dy.nomadro.cn/ops-neko/1/ +curl -sS -m 12 -o /tmp/ops.html -w 'cn_ops1_body=%{http_code} size=%{size_download}\n' https://dy.nomadro.cn/ops-neko/1/ +head -c 120 /tmp/ops.html; echo +# TCP to guest mux via DNAT path from tencent itself (local connect won't hit PREROUTING) +timeout 3 bash -c 'echo >/dev/tcp/10.9.0.2/62300' && echo guest_mux_open || echo guest_mux_closed +timeout 3 bash -c 'echo >/dev/tcp/10.9.0.2/18200' && echo guest_http_open || echo guest_http_closed +sudo iptables -t nat -S | grep OPS-NEKO +""", + 40, + ), + flush=True, + ) + t.close() + + # public .com still HTTP via FRP; ICE uses Tencent IP + v = ssh(("107.173.30.245", 22, "root", "Xiao4669805")) + print( + run( + v, + "curl -sS -m 12 -o /dev/null -w 'com_ops1=%{http_code}\\n' https://dy.nomadro.com/ops-neko/1/; " + "curl -sS -m 8 -o /dev/null -w 'com_api=%{http_code}\\n' https://dy.nomadro.com/api/health; " + "curl -sS -m 8 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health", + 40, + ), + flush=True, + ) + v.close() + print("DONE — hard refresh https://dy.nomadro.com/ops-neko/1/ (ICE via 82.157.112.245:62300)", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_shellcrash_ui_frp.py b/scripts/_fix_shellcrash_ui_frp.py new file mode 100644 index 0000000..274c189 --- /dev/null +++ b/scripts/_fix_shellcrash_ui_frp.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Fix ShellCrash /ui: FRP-aux forward :9999 + Caddy point to 127.0.0.1:9999.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print("connected", flush=True) + return c + except Exception as ex: + print(f"retry {i} {ex}", flush=True) + time.sleep(2) + raise RuntimeError("ssh fail") + + +def run(c, cmd, t=90): + print(f"$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +REMOTE = r''' +set -e +FORWARDS="-L 127.0.0.1:18014:127.0.0.1:8014 -L 127.0.0.1:14015:127.0.0.1:4015 -L 127.0.0.1:9999:127.0.0.1:9999" +for p in $(seq 9200 9207); do + FORWARDS="$FORWARDS -L 127.0.0.1:$p:127.0.0.1:$p" +done + +cat >/etc/systemd/system/dy-frp-http-aux.service </tmp/cv.txt 2>&1 && echo caddy_ok || (tail -15 /tmp/cv.txt; exit 1) +systemctl reload caddy +systemctl is-active caddy +''' + +c = connect() +run(c, REMOTE, t=120) +c.close() + +print("## public", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for u in [ + "https://dy.nomadro.com/ui/", + "https://dy.nomadro.com/ui", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.cn/ui/", + ]: + try: + r = cl.get(u) + print( + f"{u} -> {r.status_code} ctype={r.headers.get('content-type','')[:35]} " + f"body={r.text[:60]!r}", + flush=True, + ) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_fix_vps_assign_chrome_dual.py b/scripts/_fix_vps_assign_chrome_dual.py new file mode 100644 index 0000000..b6accd5 --- /dev/null +++ b/scripts/_fix_vps_assign_chrome_dual.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Clean orphan chrome on VPS assign Nekos (currently neko-7).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +FIX = r"""#!/bin/bash +set -e +echo '=== before ===' +docker ps --format '{{.Names}}' | grep -E 'douyinweb-neko-' | sort +for N in $(docker ps --format '{{.Names}}' | grep -E 'douyinweb-neko-[0-9]+$' | sort); do + echo "===== $N =====" + docker exec "$N" supervisorctl stop google-chrome || true + sleep 1 + docker exec -i "$N" python3 - <<'PY' +import os, signal, time +n=0 +for _ in range(3): + for pid in list(os.listdir("/proc")): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw or b"/opt/google/chrome" in raw: + try: + os.kill(int(pid), signal.SIGKILL); n+=1 + except Exception: + pass + time.sleep(0.4) +print("killed", n) +PY + docker exec "$N" bash -lc 'rm -f /home/neko/.config/google-chrome/SingletonCookie /home/neko/.config/google-chrome/SingletonLock /home/neko/.config/google-chrome/SingletonSocket /home/neko/.config/google-chrome/SingletonStartupLock /home/neko/.config/google-chrome/lockfile /home/neko/.config/google-chrome/DevToolsActivePort 2>/dev/null; true' + docker exec "$N" supervisorctl start google-chrome +done +sleep 20 +echo '=== after ===' +for N in $(docker ps --format '{{.Names}}' | grep -E 'douyinweb-neko-[0-9]+$' | sort); do + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1; trap=False +try: + trap=b"on_supervisor_stop" in open("/etc/neko/browser-launch.sh","rb").read() +except Exception as e: + trap=repr(e) +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw} trap={trap}") +PY +) + echo "$N $out" +done +# quick public probe +curl -sS -m 5 -o /dev/null -w 'dylive_neko7=%{http_code}\n' https://dylive.nomadro.com/neko/7/ || true +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_vps_assign_chrome_dual.sh", "w") as f: + f.write(FIX) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_fix_vps_assign_chrome_dual.sh", timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_vps_neko7_tm_sw.py b/scripts/_fix_vps_neko7_tm_sw.py new file mode 100644 index 0000000..e4edac9 --- /dev/null +++ b/scripts/_fix_vps_neko7_tm_sw.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command( + """ +docker exec douyinweb-neko-7 supervisorctl restart google-chrome +sleep 15 +docker exec -i douyinweb-neko-7 python3 <<'PY' +import json, os, re, urllib.request, time +from pathlib import Path +tabs=[] +for _ in range(10): + try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3).read()); break + except Exception: time.sleep(2) +print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or ""))) +print("tab_n", len(tabs)) +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\\x00",b" ").decode() + except Exception: continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd); print("load_ext", m.group(1) if m else None); break +# rough script presence in LES +les=Path("/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo") +hits=0 +for p in les.glob("*"): + try: + b=p.read_bytes() + if b"youtube" in b.lower() or b"dismiss" in b.lower() or b"@name" in b: + hits+=1 + except Exception: pass +print("les_scriptish_files", hits) +PY +""", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_fix_vps_neko_public_url.py b/scripts/_fix_vps_neko_public_url.py new file mode 100644 index 0000000..8611ba5 --- /dev/null +++ b/scripts/_fix_vps_neko_public_url.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Fix VPS Neko open URL: set DY_PUBLIC_BASE_URL + deploy youtube_neko.py.""" +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] +SRC = LOCAL / "backend/app/youtube_neko.py" + +DROPIN = """[Service] +Environment=DY_PUBLIC_BASE_URL=https://dylive.nomadro.com +Environment=DY_INSTALL_SHAPE=vps +Environment=DY_NEKO_HTTP_BIND=127.0.0.1 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/youtube_neko.py.urlfix", "wb") as f: + f.write(SRC.read_bytes()) + with sftp.file("/tmp/dylive_public_base.conf", "wb") as f: + f.write(DROPIN.encode()) + sftp.close() + + remote = r""" +set -e +mkdir -p /etc/systemd/system/douyinweb-api.service.d +# in-place for app file +cat /tmp/youtube_neko.py.urlfix > /opt/douyinWEB/backend/app/youtube_neko.py +sed -i 's/\r$//' /opt/douyinWEB/backend/app/youtube_neko.py +# drop-in for public base (idempotent overwrite) +cat /tmp/dylive_public_base.conf > /etc/systemd/system/douyinweb-api.service.d/public-base.conf +systemctl daemon-reload +systemctl restart douyinweb-api +sleep 3 +systemctl is-active douyinweb-api +cd /opt/douyinWEB/backend +PY=python3; [ -x .venv/bin/python ] && PY=.venv/bin/python +# verify under systemd env +systemctl show douyinweb-api -p Environment --value | tr ' ' '\n' | grep -E 'DY_PUBLIC|DY_INSTALL|DY_NEKO_HTTP' || true +$PY - <<'PY' +import os, sys +# mimic systemd env for check +os.environ.setdefault('DY_PUBLIC_BASE_URL','https://dylive.nomadro.com') +os.environ.setdefault('DY_INSTALL_SHAPE','vps') +os.environ.setdefault('DY_NEKO_HTTP_BIND','127.0.0.1') +sys.path.insert(0,'.') +# reload settings +import importlib +from app import config +importlib.reload(config) +from app import youtube_neko +importlib.reload(youtube_neko) +print('physical_dual', youtube_neko._physical_dual_edge()) +print('preferred', youtube_neko.preferred_neko_public_base()) +print('studio6', youtube_neko.public_studio_url(6)) +print('studio8', youtube_neko.public_studio_url(8)) +PY +# live API check +curl -sS -m 8 -b /tmp/cj -c /tmp/cj -X POST https://dylive.nomadro.com/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 8 -b /tmp/cj https://dylive.nomadro.com/api/youtube/assign/groups | \ + python3 -c "import sys,json; d=json.load(sys.stdin); gs=d.get('groups') or d; +[print(g.get('name'), g.get('neko_instance_id'), g.get('neko_local_studio_url') or g.get('neko_studio_url')) for g in gs if int(g.get('neko_instance_id') or 0) in (6,7,8) or 'nomad' in str(g.get('name') or '').lower()]" +""" + _i, o, e = c.exec_command(remote, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_fix_wg_oneway_live.py b/scripts/_fix_wg_oneway_live.py new file mode 100644 index 0000000..4d3d510 --- /dev/null +++ b/scripts/_fix_wg_oneway_live.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Debug one-way WG: guest->VPS works, VPS->guest fails. Live.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(port=22, user="root", pw="Xiao4669805"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected :{port}", flush=True) + return c + + +def run(c, cmd, t=60): + print(f"$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## VPS conf + keepalive + tcpdump sample", flush=True) +v = connect(22) +run(v, "cat /etc/wireguard/wg-dy.conf; echo ---; sysctl net.ipv4.conf.all.rp_filter net.ipv4.conf.wg-dy.rp_filter 2>/dev/null; iptables -L OUTPUT -n | head -15") +run( + v, + # force keepalive on server peer + dump a few packets + "wg set wg-dy peer 63+cGgkjfB3XtHZgv/fwY7czeBBMBN94EiOvK8747yA= persistent-keepalive 15; " + "timeout 8 tcpdump -ni any udp port 51820 -c 12 -tttt 2>&1 | tail -30 || true; " + "wg show wg-dy", + t=40, +) +v.close() + +print("## guest conf + ping", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "cat /etc/wireguard/wg-dy.conf; echo ---; " + "wg show wg-dy; " + "ping -c 5 -W 2 10.8.0.1 | tail -8" + "'", + t=40, +) +g.close() + +print("## recheck tunnel", flush=True) +time.sleep(3) +v = connect(22) +run( + v, + "wg show wg-dy; ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 8 -o /dev/null -w via_wg=%{http_code}\\\\n http://10.8.0.2:8014/api/health", + t=30, +) +v.close() + +with httpx.Client(follow_redirects=False, timeout=12) as cl: + for u in ["https://dy.nomadro.com/api/health", "https://dylive.nomadro.com/api/health"]: + try: + print(u, "->", cl.get(u).status_code, flush=True) + except Exception as ex: + print(u, ex, flush=True) +print("DONE", flush=True) diff --git a/scripts/_fix_wg_only_live.py b/scripts/_fix_wg_only_live.py new file mode 100644 index 0000000..c2a471f --- /dev/null +++ b/scripts/_fix_wg_only_live.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Fix wg-dy handshake only. No Neko. Live flush.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(port=22, user="root", pw="Xiao4669805"): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected :{port}", flush=True) + return c + except Exception as ex: + print(f"retry :{port} {i} {ex}", flush=True) + time.sleep(2) + raise RuntimeError("ssh fail") + + +def run(c, cmd, t=60): + print(f"$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print(f"→ {o.channel.recv_exit_status()}", flush=True) + + +print("## VPS wg bounce", flush=True) +v = connect(22) +run( + v, + "wg-quick down wg-dy; wg-quick up wg-dy; sleep 1; " + "wg show wg-dy; " + "ss -ulnp | grep 51820 || true", +) +v.close() + +print("## guest wg bounce", flush=True) +g = connect(4014, "eric", "4669805") +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy; wg-quick up wg-dy; sleep 2; " + "wg show wg-dy; " + "ping -c 3 -W 2 10.8.0.1 | tail -5" + "'", + t=50, +) +g.close() + +print("## wait handshake 8s", flush=True) +time.sleep(8) + +v = connect(22) +run( + v, + "wg show wg-dy; ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 10 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health", + t=40, +) +v.close() + +print("## public", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in ["https://dy.nomadro.com/api/health", "https://dy.nomadro.com/", "https://dylive.nomadro.com/api/health"]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) +print("DONE", flush=True) diff --git a/scripts/_fix_yt_thumbs_neko_ui_dual.py b/scripts/_fix_yt_thumbs_neko_ui_dual.py new file mode 100644 index 0000000..4f81f44 --- /dev/null +++ b/scripts/_fix_yt_thumbs_neko_ui_dual.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +"""Fix YT profile thumbs + rewrite Neko UI copy; deploy dual VPS.""" +from __future__ import annotations + +import hashlib +import sys +import time +import tarfile +import io +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805" +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + return c + except Exception as e: + print("retry", host, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, script, timeout=600): + _i, o, e = c.exec_command(script, timeout=timeout) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def put(c, data: bytes, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "wb") as f: + f.write(data) + sftp.close() + + +# --- 1) Fix UI copy locally --- +panel = ROOT / "frontend/src/components/YtRelayProStatusPanel.tsx" +text = panel.read_text(encoding="utf-8") +repls = [ + ("打开物理机配对实例", "打开远程配对实例"), + ("请先选择远程实例", "请先选择远程实例"), + ("未绑定:在下方选物理机实例,或去 Neko 页完成配对", "未绑定:在下方选远程实例,或去 Neko 页完成对端配对(双 VPS 可选)"), + ("物理机实例", "远程实例"), + ("目录为空:请到 Neko 页完成物理机配对。", "目录为空:未配对对端;双 VPS 可只用本机 Neko,无需远程。"), + ( + "本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{", + "本机 Neko #{instanceId}:开关=启停容器(新建默认关)。密码{", + ), +] +# The last one uses template - fix the actual source string +repls[-1] = ( + "本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{", + "本机 Neko #{instanceId}:开关控制容器启停(新建默认关)。密码{", +) +# In TSX it's JSX with {instanceId} +old_help = '本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{" "}' +# read exact lines +for a, b in [ + ("打开物理机配对实例", "打开远程配对实例"), + ("未绑定:在下方选物理机实例,或去 Neko 页完成配对", "未绑定:可选远程实例;双 VPS 通常只用本机 Neko"), + ("物理机实例", "远程实例"), + ("目录为空:请到 Neko 页完成物理机配对。", "目录为空:未配对对端。双 VPS 可只用本机,忽略此项。"), +]: + if a not in text: + print("MISSING_STR", a, flush=True) + else: + text = text.replace(a, b) + print("replaced", a[:30], flush=True) + +# help text +old = "本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{" +# actual file content: +import re +text2, n = re.subn( + r"本机 Neko #\{instanceId\} 默认停止;启用即启停容器。", + "本机 Neko #{instanceId}:启用=启动容器,关闭=停止(新建默认关)。", + text, + count=1, +) +print("help_n", n, flush=True) +text = text2 +panel.write_text(text, encoding="utf-8") + +# OpsNekoHubCredentialsCard +ops = ROOT / "frontend/src/components/OpsNekoHubCredentialsCard.tsx" +if ops.exists(): + ot = ops.read_text(encoding="utf-8") + ot2 = ot.replace("加载物理机配对凭证", "加载远程配对凭证") + if ot2 != ot: + ops.write_text(ot2, encoding="utf-8") + print("ops card text updated", flush=True) + +FIX_THUMBS = r''' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, re, urllib.request +from app.db import _connect, _lock + +def exists(url: str) -> bool: + try: + urllib.request.urlopen(url, timeout=4).read(8) + return True + except Exception: + return False + +def rewrite_url(u: str) -> str: + u = str(u or "") + u2 = u.replace("https://dy.nomadro.com/douyin-covers", "https://s3.nomadro.com/douyin-covers") + u2 = u2.replace("http://dy.nomadro.com/douyin-covers", "https://s3.nomadro.com/douyin-covers") + return u2 + +with _lock: + conn = _connect() + cols = [r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()] + print("cols_has_yt_profile", "yt_profile_json" in cols) + rows = conn.execute( + "SELECT id, name, yt_profile_json FROM shorts_channels WHERE yt_profile_json IS NOT NULL AND yt_profile_json != ''" + ).fetchall() + fixed = 0 + cleared = 0 + ok = 0 + for rid, name, raw in rows: + try: + data = json.loads(raw) + except Exception: + continue + changed = False + thumb = str(data.get("thumb_url") or "").strip() + thumbs = data.get("thumbnails") if isinstance(data.get("thumbnails"), dict) else {} + # rewrite hosts + new_thumb = rewrite_url(thumb) + if new_thumb != thumb: + data["thumb_url"] = new_thumb + thumb = new_thumb + changed = True + for k in ("default", "medium", "high"): + node = thumbs.get(k) if isinstance(thumbs.get(k), dict) else None + if not node: + continue + ou = str(node.get("url") or "") + nu = rewrite_url(ou) + if nu != ou: + node["url"] = nu + changed = True + # if still broken, prefer thumb_cdn youtube googleusercontent + cdn = str(data.get("thumb_cdn") or "").strip() + check = str(data.get("thumb_url") or "").strip() + if check.startswith("http") and not exists(check): + if cdn.startswith("http") and exists(cdn): + data["thumb_url"] = cdn + data["thumbnails"] = { + "default": {"url": cdn}, + "medium": {"url": cdn}, + } + changed = True + print("fallback_cdn", name, cdn[:60]) + else: + # blank so UI can refresh later rather than letter-from-broken + data["thumb_url"] = cdn if cdn.startswith("http") else "" + if data.get("thumbnails"): + for k, node in list(data["thumbnails"].items()): + if isinstance(node, dict): + node["url"] = data["thumb_url"] + changed = True + cleared += 1 + print("broken", name, check[-50:]) + check = data["thumb_url"] + if check.startswith("http") and exists(check): + ok += 1 + if changed: + conn.execute( + "UPDATE shorts_channels SET yt_profile_json=? WHERE id=?", + (json.dumps(data, ensure_ascii=False), rid), + ) + fixed += 1 + conn.commit() + print("fixed", fixed, "ok_now", ok, "cleared_or_cdn", cleared) +PY +''' + +for label, host in [("dylive", DYLIVE), ("dy", DY)]: + print(f"\n######## fix thumbs {label} ########", flush=True) + c = connect(host) + print(run(c, FIX_THUMBS, timeout=300), flush=True) + c.close() + +# --- deploy FE files + rebuild on dy, sync to dylive --- +files = [ + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/components/OpsNekoHubCredentialsCard.tsx", + "frontend/src/lib/api.js", + "backend/app/session_auth.py", + "backend/app/youtube_neko.py", +] + +print("\n######## deploy sources to dy + build ########", flush=True) +c = connect(DY) +for rel in files: + p = ROOT / rel.replace("/", "\\") + if p.exists(): + put(c, p.read_bytes(), f"/opt/douyinWEB/{rel}") + print("put", rel, flush=True) +print( + run( + c, + r""" +set -e +systemctl restart douyinweb-api +cd /opt/douyinWEB/frontend +export NODE_OPTIONS=--max-old-space-size=3072 +npm run build 2>&1 | tail -25 +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +tar -C /opt/douyinWEB/frontend -czf /tmp/next-fe-neko-ui.tgz .next +# also pack changed src for dylive +tar -C /opt/douyinWEB -czf /tmp/src-neko-ui.tgz \ + frontend/src/components/YtRelayProStatusPanel.tsx \ + frontend/src/components/OpsNekoHubCredentialsCard.tsx \ + frontend/src/lib/api.js \ + backend/app/session_auth.py \ + backend/app/youtube_neko.py +ls -lh /tmp/next-fe-neko-ui.tgz /tmp/src-neko-ui.tgz +""", + timeout=700, + ), + flush=True, +) +sftp = c.open_sftp() +sftp.get("/tmp/next-fe-neko-ui.tgz", str(ROOT / "scripts/_next-fe-neko-ui.tgz")) +sftp.get("/tmp/src-neko-ui.tgz", str(ROOT / "scripts/_src-neko-ui.tgz")) +sftp.close() +c.close() + +print("\n######## deploy to dylive ########", flush=True) +c = connect(DYLIVE) +put(c, (ROOT / "scripts/_src-neko-ui.tgz").read_bytes(), "/tmp/src-neko-ui.tgz") +put(c, (ROOT / "scripts/_next-fe-neko-ui.tgz").read_bytes(), "/tmp/next-fe-neko-ui.tgz") +print( + run( + c, + r""" +set -e +tar -C /opt/douyinWEB -xzf /tmp/src-neko-ui.tgz +systemctl stop douyinweb-web || true +rm -rf /opt/douyinWEB/frontend/.next.bak_neko_ui +mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_neko_ui 2>/dev/null || true +tar -C /opt/douyinWEB/frontend -xzf /tmp/next-fe-neko-ui.tgz +systemctl restart douyinweb-api +systemctl start douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +# hash check +python3 - <<'PY' +import hashlib, pathlib +for rel in [ + 'backend/app/youtube_neko.py', + 'frontend/src/components/YtRelayProStatusPanel.tsx', + 'frontend/src/lib/api.js', +]: + p=pathlib.Path('/opt/douyinWEB')/rel + print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel) +PY +grep -n '远程实例\|双 VPS\|打开远程' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -10 +""", + timeout=120, + ), + flush=True, +) +c.close() + +# trigger profile refresh on both so CDN fills missing +REFRESH = r''' +cd /opt/douyinWEB/backend +# call local API with cookie is hard; invoke python directly +./.venv/bin/python - <<'PY' +import asyncio +from app import youtube_manage +async def main(): + r = await youtube_manage.refresh_stale_yt_profiles(max_age_sec=0, limit=50) + print(r) +asyncio.run(main()) +PY +''' +for label, host in [("dylive", DYLIVE), ("dy", DY)]: + print(f"\n######## refresh profiles {label} ########", flush=True) + c = connect(host) + print(run(c, REFRESH, timeout=300), flush=True) + c.close() + +print("ALL_DONE", flush=True) diff --git a/scripts/_force_sync_youtube_live.py b/scripts/_force_sync_youtube_live.py new file mode 100644 index 0000000..38d5a4f --- /dev/null +++ b/scripts/_force_sync_youtube_live.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import hashlib +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parents[1] / "backend" / "app" / "youtube_live.py" +LOCAL_SHA = hashlib.sha256(LOCAL.read_bytes()).hexdigest()[:16] +print("local", LOCAL_SHA, "has_offline_hit", b"public_offline_hit" in LOCAL.read_bytes()) + + +def check(host, port, user, pw, sudo=False): + print(f"\n== {user}:{port} ==") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + # force write via tmp + install + tmp = "/tmp/youtube_live_force.py" + data = LOCAL.read_bytes() + with sftp.file(tmp, "wb") as f: + f.write(data) + sftp.close() + dst = "/opt/douyinWEB/backend/app/youtube_live.py" + + def run(cmd, t=60): + _, o, e = c.exec_command(cmd, timeout=t) + o.channel.settimeout(t) + try: + return (o.read() + e.read()).decode("utf-8", "replace") + except Exception as ex: + return str(ex) + + if sudo: + print( + run( + f"echo '{pw}' | sudo -S -p '' bash -lc \"cp -a {dst} {dst}.bak_oa; cat {tmp} > {dst}; sha256sum {dst}; grep -c public_offline_hit {dst}; systemctl restart douyinweb-api\"", + 50, + ) + ) + else: + print(run(f"cp -a {dst} {dst}.bak_oa; cat {tmp} > {dst}; sha256sum {dst}; grep -c public_offline_hit {dst}; systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", 50)) + import time + + for i in range(10): + time.sleep(2) + h = run("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip() + print(" health", h) + if h == "200": + break + # introspect running code + print( + run( + """ +/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import inspect +from app import youtube_live +src = inspect.getsource(youtube_live._build_live_map_unlocked) +print('module_file', youtube_live.__file__) +print('has_public_offline_hit', 'public_offline_hit' in src) +print('has_oauth_assign', 'Assign cards that bind' in src or 'pk_to_assign' in src) +PY +""" + ) + ) + c.close() + + +check("107.173.30.245", 22, "root", "Xiao4669805", False) +check("107.173.30.245", 4014, "eric", "4669805", True) diff --git a/scripts/_harden_chrome_oom_guard.py b/scripts/_harden_chrome_oom_guard.py new file mode 100644 index 0000000..cf4bdcc --- /dev/null +++ b/scripts/_harden_chrome_oom_guard.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Harden dylive against Chrome OOM on 3.8G host (no login wipe, keep sing-box/frpp/wg).""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=600): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-20000:] if len(out) > 20000 else out, flush=True) + return code, out + + +c = ssh() +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/neko/browser-launch.sh"), "/tmp/browser-launch.sh") +sftp.put(str(ROOT / "backend/app/youtube_neko.py"), "/tmp/youtube_neko.py") +sftp.close() + +code, _ = run( + c, + r""" +set -euo pipefail + +echo ===1_SWAP=== +# Keep existing /swapfile; add /swapfile2 (+3G) so host has 4G swap headroom. +if [ ! -f /swapfile2 ]; then + fallocate -l 3G /swapfile2 || dd if=/dev/zero of=/swapfile2 bs=1M count=3072 status=progress + chmod 600 /swapfile2 + mkswap /swapfile2 +fi +swapon /swapfile2 2>/dev/null || true +grep -q '/swapfile2' /etc/fstab || echo '/swapfile2 none swap sw 0 0' >> /etc/fstab +# Use swap before hard OOM (was thrashing at 100% of 1G). +sysctl -w vm.swappiness=60 +grep -q '^vm.swappiness' /etc/sysctl.d/99-douyinweb-oom.conf 2>/dev/null \ + || printf 'vm.swappiness=60\nvm.vfs_cache_pressure=50\n' > /etc/sysctl.d/99-douyinweb-oom.conf +sysctl -p /etc/sysctl.d/99-douyinweb-oom.conf || true +swapon --show +free -h + +echo ===2_API_OOM_PREF=== +# Prefer reclaim/kill API before Neko/Chrome. Soft memory high-water. +mkdir -p /etc/systemd/system/douyinweb-api.service.d +cat > /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf <<'EOF' +[Service] +# Positive = more likely chosen by host OOM killer than Neko/Chrome (-800). +OOMScoreAdjust=300 +# Soft pressure: reclaim before hard OOM; hard cap leaves headroom for Chrome. +MemoryHigh=900M +MemoryMax=1400M +EOF +systemctl daemon-reload +systemctl restart douyinweb-api.service +sleep 3 +systemctl is-active douyinweb-api.service +systemctl show douyinweb-api.service -p OOMScoreAdjust -p MemoryHigh -p MemoryMax -p MemoryCurrent + +echo ===3_BROWSER_LAUNCH=== +install -m 0755 /tmp/browser-launch.sh /opt/douyinWEB/backend/neko/browser-launch.sh +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py +# Bind-mount is live; soft-restart Chrome so new flags + oom_score apply (profile untouched). +if docker inspect douyinweb-neko-7 --format '{{.State.Running}}' 2>/dev/null | grep -q true; then + docker update --oom-score-adj=-800 douyinweb-neko-7 || true + docker exec douyinweb-neko-7 sh -c 'pkill -TERM -f /opt/google/chrome/chrome 2>/dev/null; true' + sleep 6 +fi + +echo ===4_VERIFY=== +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import youtube_neko as yn + +nid=7 +print("oom_inspect", yn._run(["docker","inspect",yn._container_name(nid),"--format","{{.HostConfig.OomScoreAdj}} {{.HostConfig.Memory}}"], timeout=15)[1].strip()) +# wait CDP +for i in range(25): + tabs=yn._cdp_fetch_tabs(nid) + pages=[t for t in tabs if (t.get("type") or "page")=="page"] + print("wait", i, "pages", len(pages)) + if pages: + break + time.sleep(2) +studio="https://studio.youtube.com/" +for t in yn._cdp_fetch_tabs(nid): + u=str(t.get("url") or "") + if "livestreaming" in u.lower(): + studio=u + break +print("ensure", yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio)) +time.sleep(6) +sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0) +print("sig", json.dumps({k:sig.get(k) for k in ("ok","live_status","control_ready","on_air","url","text")}, ensure_ascii=False)[:500]) +# chrome oom scores inside +code,out=yn._run(["docker","exec",yn._container_name(nid),"sh","-c", + "for p in /proc/[0-9]*; do cmd=$(tr '\\0' ' ' <$p/cmdline 2>/dev/null); case \"$cmd\" in *'/opt/google/chrome/chrome '*) echo ${p#/proc/} $(cat $p/oom_score_adj 2>/dev/null) $(echo $cmd|cut -c1-60);; esac; done | head -15"], timeout=20) +print("chrome_oom", out[:1500]) +PY + +free -h +swapon --show +docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}}' douyinweb-neko-7 +# Untouchable units still up +systemctl is-active sing-box.service frpp.service 'wg-quick@wg-dy.service' || true +""", +) +c.close() +print("exit", code, time.strftime("%H:%M:%S")) +raise SystemExit(code) diff --git a/scripts/_harden_dylive_api_mem.py b/scripts/_harden_dylive_api_mem.py new file mode 100644 index 0000000..48e1eda --- /dev/null +++ b/scripts/_harden_dylive_api_mem.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Inspect + harden douyinweb-api memory cgroup on dylive.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + + +def run(cmd: str, t: int = 120) -> str: + print("\n=====", cmd[:100].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return out + + +run( + r""" +set +e +echo '=== unit files ===' +systemctl cat douyinweb-api.service | sed -n '1,120p' +echo +echo '=== drop-ins ===' +ls -la /etc/systemd/system/douyinweb-api.service.d/ 2>/dev/null || echo none +for f in /etc/systemd/system/douyinweb-api.service.d/*.conf; do + [ -f "$f" ] || continue + echo "--- $f ---"; cat "$f" +done +echo +echo '=== effective ===' +systemctl show douyinweb-api.service -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,MemoryAccounting,OOMPolicy,OOMScoreAdjust,FragmentPath,DropInPaths +echo +echo '=== cgroup v2 ===' +CG=$(systemctl show douyinweb-api.service -p ControlGroup --value) +echo CG=$CG +if [ -n "$CG" ]; then + for f in memory.max memory.high memory.current memory.swap.max memory.events; do + p="/sys/fs/cgroup${CG}/$f" + [ -f "$p" ] && echo "$f=$(cat $p)" + done +fi +echo +echo '=== api rss now ===' +ps -o pid,rss,cmd -C python | grep -E 'uvicorn|app.main' | head -5 +free -h | head -3 +""" +) + +# Harden: MemoryHigh=700M MemoryMax=900M (leave room for neko+ffmpeg on 3.8G host) +# OOMScoreAdjust=400 so API dies before chrome if global OOM (chrome protected -800) +# Only change drop-in, don't touch unrelated units +run( + r""" +set -euo pipefail +mkdir -p /etc/systemd/system/douyinweb-api.service.d +cat > /etc/systemd/system/douyinweb-api.service.d/memory.conf <<'EOF' +[Service] +MemoryAccounting=yes +# Soft throttle early; hard kill if ballooning (was ~1.4G max / historically 2G RSS) +MemoryHigh=700M +MemoryMax=900M +MemorySwapMax=256M +OOMPolicy=kill +# Prefer kill API over Neko Chrome on global OOM (chrome uses oom_score_adj=-800) +OOMScoreAdjust=400 +EOF +systemctl daemon-reload +systemctl restart douyinweb-api.service +sleep 4 +systemctl is-active douyinweb-api.service +systemctl show douyinweb-api.service -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,OOMPolicy,OOMScoreAdjust +CG=$(systemctl show douyinweb-api.service -p ControlGroup --value) +echo CG=$CG +for f in memory.max memory.high memory.current memory.swap.max; do + p="/sys/fs/cgroup${CG}/$f" + [ -f "$p" ] && echo "$f=$(cat $p)" +done +# smoke +curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 200; echo +free -h | head -3 +""" +) +c.close() +print("DONE") diff --git a/scripts/_harden_dylive_api_mem2.py b/scripts/_harden_dylive_api_mem2.py new file mode 100644 index 0000000..ff758b4 --- /dev/null +++ b/scripts/_harden_dylive_api_mem2.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Tighten dylive API memory drop-in in-place (wins over other drop-ins).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + +cmd = r""" +set -euo pipefail +# Single source of truth — later-sorted name so it wins +rm -f /etc/systemd/system/douyinweb-api.service.d/memory.conf +cat > /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf <<'EOF' +[Service] +MemoryAccounting=yes +# Soft reclaim under pressure; hard kill before host global OOM (hist ~2G RSS) +MemoryHigh=700M +MemoryMax=900M +MemorySwapMax=256M +OOMPolicy=kill +# Prefer kill API over Neko Chrome (chrome oom_score_adj=-800) +OOMScoreAdjust=400 +EOF +systemctl daemon-reload +systemctl restart douyinweb-api.service +sleep 6 +systemctl is-active douyinweb-api.service +echo '--- show ---' +systemctl show douyinweb-api.service -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,OOMPolicy,OOMScoreAdjust +CG=$(systemctl show douyinweb-api.service -p ControlGroup --value) +echo CG=$CG +for f in memory.max memory.high memory.current memory.swap.max memory.events; do + p="/sys/fs/cgroup${CG}/$f" + [ -f "$p" ] && echo "$f=$(cat $p)" +done +echo '--- health ---' +curl -sS -m 10 http://127.0.0.1:8014/api/health +echo +sleep 8 +curl -sS -m 10 http://127.0.0.1:8014/api/health +echo +free -h | head -3 +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_heal_shorts_empty_clips.py b/scripts/_heal_shorts_empty_clips.py new file mode 100644 index 0000000..685c509 --- /dev/null +++ b/scripts/_heal_shorts_empty_clips.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +"""Deploy clip-reconcile fix + immediately heal stuck scheduled-empty clips on dylive.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/db.py", + "backend/app/clip_retention.py", +] + +HEAL = r''' +set -e +install -m 644 /tmp/_dy_db.py /opt/douyinWEB/backend/app/db.py +install -m 644 /tmp/_dy_ret.py /opt/douyinWEB/backend/app/clip_retention.py +# strip CRLF +python3 -c "from pathlib import Path +for p in [Path('/opt/douyinWEB/backend/app/db.py'), Path('/opt/douyinWEB/backend/app/clip_retention.py')]: + p.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) + print('lf', p)" + +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service + +# Direct heal today's stuck jobs (empty clip + scheduled) +python3 <<'PY' +import sqlite3, time +conn=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +day=time.strftime('%Y-%m-%d', time.gmtime(time.time()+8*3600)) # rough BJ +# better BJ +import datetime +BJ=datetime.timezone(datetime.timedelta(hours=8)) +day=datetime.datetime.now(BJ).strftime('%Y-%m-%d') +now=time.time() +before=conn.execute("SELECT COUNT(*) FROM shorts_jobs WHERE push_date=? AND status='scheduled' AND IFNULL(clip_path,'')='' AND IFNULL(youtube_video_id,'')=''",(day,)).fetchone()[0] +cur=conn.execute(""" +UPDATE shorts_jobs +SET status='pending', clip_path='', clip_seconds=0, upload_at=0, + error='成片路径为空,已重新排队录制', finished_at=0, updated_at=? +WHERE push_date=? AND status IN ('scheduled','recorded','uploading') + AND IFNULL(youtube_video_id,'')='' + AND IFNULL(clip_path,'')='' +""",(now, day)) +conn.commit() +print('day', day, 'stuck_empty_before', before, 'healed', cur.rowcount) +rows=conn.execute("SELECT status, COUNT(*) c FROM shorts_jobs WHERE push_date=? GROUP BY status",(day,)).fetchall() +print('after', {r[0]:r[1] for r in rows}) +conn.close() +PY + +# bump record concurrency briefly via settings if too low +python3 <<'PY' +import sqlite3 +conn=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +for k,v in [('shorts_max_concurrent','3')]: + row=conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone() + print('before', k, row[0] if row else None) + if row: + conn.execute('UPDATE kv_settings SET value=? WHERE key=?',(v,k)) + else: + conn.execute('INSERT INTO kv_settings(key,value) VALUES(?,?)',(k,v)) +conn.commit() +print('set shorts_max_concurrent=3 for catch-up') +conn.close() +PY + +curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo +''' + + +def put_host(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + sftp.put(str(ROOT / "backend/app/db.py"), "/tmp/_dy_db.py") + sftp.put(str(ROOT / "backend/app/clip_retention.py"), "/tmp/_dy_ret.py") + with sftp.file("/tmp/_dy_heal_shorts.sh", "w") as f: + f.write(HEAL.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_heal_shorts.sh" if sudo else "bash /tmp/_dy_heal_shorts.sh" + _, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +put_host("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +put_host("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + +# verify public +time.sleep(4) +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +base = "https://dylive.nomadro.com" +req = urllib.request.Request( + base + "/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + method="POST", + headers={"Content-Type": "application/json"}, +) +op.open(req, timeout=30) +with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) +board = st.get("board") or {} +print( + "dylive after: active_rec=", st.get("active_records"), + "active_up=", st.get("active_uploads"), + "gap=", st.get("quota_gap"), + "min_unmet=", board.get("min_unmet"), +) +print("done") diff --git a/scripts/_health_neko_core_ro.py b/scripts/_health_neko_core_ro.py new file mode 100644 index 0000000..926693d --- /dev/null +++ b/scripts/_health_neko_core_ro.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read-only health: VPS hub binds + physical ops-neko + relay/live gate.""" +from __future__ import annotations + +import json +import sys +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw, script, sudo=False, timeout=90): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120) + sftp = c.open_sftp() + path = f"/tmp/_health_{port}.sh" + with sftp.file(path, "w") as f: + f.write(script) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash {path}" if sudo else f"bash {path}" + _i, o, e = c.exec_command(cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +def http_json(url: str, timeout: int = 12): + try: + req = urllib.request.Request(url, headers={"User-Agent": "dy-health/1"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + body = r.read().decode("utf-8", "replace") + code = r.status + try: + return code, json.loads(body) + except Exception: + return code, body[:500] + except Exception as e: + return None, str(e) + + +VPS = r"""#!/bin/bash +set +e +echo '=== mem ===' +free -h | head -3 +echo '=== local neko containers ===' +docker ps -a --format '{{.Names}} {{.Status}}' | grep -E 'douyinweb-neko' | sort +echo '=== assign binds (DB) ===' +python3 - <<'PY' +import sqlite3 +db='/opt/douyinWEB/backend/data/monitor.db' +con=sqlite3.connect(db); con.row_factory=sqlite3.Row +rows=con.execute(''' +SELECT name, neko_instance_id, neko_enabled, neko_open_prefer, + ops_neko_bind_url, ops_neko_bind_label, ops_neko_bind_edge +FROM yt_assign_groups ORDER BY neko_instance_id +''').fetchall() +for r in rows: + d=dict(r) + print(f"id={d.get('neko_instance_id')} en={d.get('neko_enabled')} prefer={d.get('neko_open_prefer')} name={d.get('name')}") + print(f" bind={d.get('ops_neko_bind_url')} label={d.get('ops_neko_bind_label')} edge={d.get('ops_neko_bind_edge')}") +PY +echo '=== ops catalog / edge sync (if tables) ===' +python3 - <<'PY' +import sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +for t in con.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1").fetchall(): + if any(x in t[0].lower() for x in ('ops','neko','relay','studio')): + print('table', t[0]) +PY +echo '=== api health snippets ===' +curl -sS -m 8 http://127.0.0.1:8014/api/health 2>/dev/null | head -c 400; echo +curl -sS -m 8 http://127.0.0.1:8014/api/youtube/assign/groups 2>/dev/null | python3 -c 'import sys,json +try: + d=json.load(sys.stdin); gs=d if isinstance(d,list) else d.get("groups") or d.get("items") or [] + print("groups", len(gs)) + for g in gs[:12]: + print({k:g.get(k) for k in ("name","neko_instance_id","neko_enabled","neko_open_prefer","ops_neko_bind_url","ops_neko_open_url","relay_enabled","live") if k in g or True}) +except Exception as e: + print("err",e, sys.stdin.read()[:200] if False else "") +' 2>/dev/null | head -80 +""" + +PHYS = r"""#!/bin/bash +set +e +echo '=== ops-neko containers ===' +docker ps -a --format '{{.Names}} {{.Status}}' | grep -E 'ops-neko|neko' | sort +echo '=== ops-neko chrome/TM (no changes) ===' +for N in douyinweb-ops-neko-1 douyinweb-ops-neko-2; do + docker inspect "$N" >/dev/null 2>&1 || continue + echo "-- $N --" + docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +from pathlib import Path +mains=0; load=False; sw=-1 +for pid in os.listdir('/proc'): + if not pid.isdigit(): continue + try: raw=open(f'/proc/{pid}/cmdline','rb').read() + except: continue + if not raw: continue + if b'google-chrome' in raw and b'--type=' not in raw and b'crashpad' not in raw and b'browser-launch' not in raw: + mains+=1 + if b'load-extension' in raw and b'dhdgff' in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=3).read()) + sw=sum(1 for t in tabs if t.get('type')=='service_worker' and 'dhdgff' in (t.get('url') or '')) + urls=[(t.get('type'), (t.get('url') or '')[:100]) for t in tabs if t.get('type') in ('page','service_worker') and 'doubleclick' not in (t.get('url') or '')][:8] +except Exception as e: + tabs=[]; urls=[str(e)]; sw=-1 +cookie=Path('/home/neko/.config/google-chrome/Default/Cookies') +print('mains',mains,'load_ext',load,'tm_sw',sw,'cookies_bytes', cookie.stat().st_size if cookie.exists() else 0) +for u in urls: print(' ', u) +PY +done +echo '=== local http ops ports ===' +for p in 18200 18201 9200 9201 9202 9203; do + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$p/ 2>/dev/null || echo x) + echo "127.0.0.1:$p $code" +done +echo '=== cn public ===' +curl -sS -m 8 -o /dev/null -w 'cn_ops1=%{http_code}\n' https://dy.nomadro.cn/ops-neko/1/ 2>/dev/null || curl -sS -m 8 -o /dev/null -w 'cn_neko_ops_guess=%{http_code}\n' https://dy.nomadro.cn/neko/ops/1/ 2>/dev/null +# discover ops open paths from api if any +curl -sS -m 5 http://127.0.0.1:8014/api/ops-neko/status 2>/dev/null | head -c 800; echo +""" + + +def main(): + print("########## VPS ##########") + print(ssh("107.173.30.245", 22, "root", "Xiao4669805", VPS, sudo=False)) + print("########## PHYSICAL ##########") + print(ssh("107.173.30.245", 4014, "eric", "4669805", PHYS, sudo=True, timeout=120)) + print("########## PUBLIC ##########") + for url in [ + "https://dylive.nomadro.com/api/health", + "https://dy.nomadro.cn/api/health", + "https://dylive.nomadro.com/neko/7/", + "https://dy.nomadro.cn/neko/3/", + ]: + code, body = http_json(url) if url.endswith("health") else (None, None) + if url.endswith("health"): + print(url, code, str(body)[:200]) + else: + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=10) as r: + print(url, r.status) + except Exception as e: + print(url, "ERR", e) + + +if __name__ == "__main__": + main() diff --git a/scripts/_hotfix_shorts_pull_pack.py b/scripts/_hotfix_shorts_pull_pack.py new file mode 100644 index 0000000..3f28d13 --- /dev/null +++ b/scripts/_hotfix_shorts_pull_pack.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +"""Hotfix pull-forward packing + verify due slots.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +LOCAL = ROOT / "backend/app/shorts_schedule.py" + +SCRIPT = r'''#!/bin/bash +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +src=Path('/tmp/_dy_shorts_schedule.py') +dst=Path('/opt/douyinWEB/backend/app/shorts_schedule.py') +dst.write_bytes(src.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')) +print('ok', dst.stat().st_size) +PY +cd /opt/douyinWEB +. backend/.venv/bin/activate +python -m py_compile backend/app/shorts_schedule.py +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +cd backend +python <<'PY' +import sys, sqlite3, time, datetime +sys.path.insert(0, "/opt/douyinWEB/backend") +from app.shorts_schedule import fleet_pace_plan, pull_forward_due_uploads +print("pace", fleet_pace_plan()) +print("pulled", pull_forward_due_uploads()) +BJ = datetime.timezone(datetime.timedelta(hours=8)) +now = time.time() +day = datetime.datetime.now(BJ).strftime("%Y-%m-%d") +con = sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +due = fut = 0 +hours = {} +q = ( + "SELECT upload_at FROM shorts_jobs WHERE push_date=? " + "AND status IN ('scheduled','recorded') AND IFNULL(clip_path,'')!=''" +) +for (ua0,) in con.execute(q, (day,)): + ua = float(ua0 or 0) + if ua <= now + 90: + due += 1 + else: + fut += 1 + if ua > 0: + h = datetime.datetime.fromtimestamp(ua, BJ).hour + hours[h] = hours.get(h, 0) + 1 +print("due_now", due, "future", fut, "by_hour", dict(sorted(hours.items()))) +# next 8 +print("next:") +for r in con.execute( + "SELECT upload_at, status, substr(channel_pk,1,8) FROM shorts_jobs " + "WHERE push_date=? AND status IN ('scheduled','recorded') AND IFNULL(clip_path,'')!='' " + "ORDER BY CASE WHEN upload_at<=0 THEN 1e18 ELSE upload_at END LIMIT 8", + (day,), +): + ua = float(r[0] or 0) + bj = datetime.datetime.fromtimestamp(ua, BJ).strftime("%H:%M:%S") if ua else "-" + print(bj, "in", int(ua - now) if ua else "?", "s", r[1], r[2]) +con.close() +PY +''' + + +def run(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + data = LOCAL.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file("/tmp/_dy_shorts_schedule.py", "wb") as f: + f.write(data) + with sftp.file("/tmp/_dy_pace_pull.sh", "w") as f: + f.write(SCRIPT.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_pace_pull.sh" if sudo else "bash /tmp/_dy_pace_pull.sh" + _, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +run("vps-dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +run("phys-dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("DONE") diff --git a/scripts/_hotfix_timeslot_test_kick.py b/scripts/_hotfix_timeslot_test_kick.py new file mode 100644 index 0000000..85a9474 --- /dev/null +++ b/scripts/_hotfix_timeslot_test_kick.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Hotfix timeslot-test kick (non-blocking) on dylive API.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/app/youtube_relay_pipeline.py"), "/tmp/youtube_relay_pipeline.py") +sftp.close() + +cmd = r""" +set -euo pipefail +install -m 0644 /tmp/youtube_relay_pipeline.py /opt/douyinWEB/backend/app/youtube_relay_pipeline.py +systemctl restart douyinweb-api +for i in $(seq 1 40); do curl -sS -m 2 http://127.0.0.1:8014/api/health >/dev/null 2>&1 && break; sleep 1; done +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +echo -n 'next:' +curl -sS -m 45 -b "$CS" -o /tmp/next.json -w '%{http_code}' -X POST \ + http://127.0.0.1:8014/api/youtube/relay/timeslot-test/next +echo +python3 -c 'import json;d=json.load(open("/tmp/next.json"));print(d.get("timeslot_test_next"), d.get("settings",{}).get("youtube_relay_timeslot_test"), d.get("settings",{}).get("youtube_relay_timeslot_test_group_id"))' +# leave test off after smoke so we do not strand operator mid-test unexpectedly +curl -sS -m 20 -b "$CS" -X POST http://127.0.0.1:8014/api/youtube/relay/timeslot-test \ + -H 'Content-Type: application/json' -d '{"enabled":false}' >/dev/null +echo DONE +""" +_, o, e = c.exec_command(cmd, timeout=180) +print((o.read() + e.read()).decode("utf-8", "replace")) +code = o.channel.recv_exit_status() +c.close() +raise SystemExit(code) diff --git a/scripts/_hunt_opsneko_profile_bak.py b/scripts/_hunt_opsneko_profile_bak.py new file mode 100644 index 0000000..d68ef16 --- /dev/null +++ b/scripts/_hunt_opsneko_profile_bak.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Hunt for recoverable Secure Preferences / Cookies backups for ops-neko profiles.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +set -e +echo "===== Secure Preferences sizes =====" +for i in 1 2; do + p=/opt/douyinWEB/backend/data/ops_neko/profiles/$i/Default + echo "--- $i ---" + ls -la "$p/Secure Preferences" "$p/Preferences" 2>/dev/null + wc -c "$p/Secure Preferences" 2>/dev/null + echo "content:"; cat "$p/Secure Preferences"; echo + # any bak/old copies nearby + find "$p" -maxdepth 2 -iname '*secure*' -o -iname '*prefer*' 2>/dev/null | head -40 + ls -la "$p"/.* 2>/dev/null | head -20 || true +done + +echo "===== search host for larger Secure Preferences copies =====" +find /opt/douyinWEB /tmp /var/tmp /home/eric -name 'Secure Preferences' 2>/dev/null | while read f; do + sz=$(wc -c < "$f") + echo "$sz $f" +done | sort -n | tail -30 + +echo "===== Accounts dirs =====" +for i in 1 2; do + echo "--- profile $i Accounts ---" + find /opt/douyinWEB/backend/data/ops_neko/profiles/$i/Default/Accounts -type f 2>/dev/null | head -30 + ls -la /opt/douyinWEB/backend/data/ops_neko/profiles/$i/Default/Accounts 2>/dev/null +done + +echo "===== cookie auth names =====" +for i in 1 2; do + python3 - </dev/null | head -40 +for pref in /opt/douyinWEB/backend/data/neko/profiles/*/Default/Preferences; do + [ -f "$pref" ] || continue + python3 - </dev/null | head || echo no_zfs +ls /opt/douyinWEB/backend/data/ops_neko/profiles/ +# docker volume backups +ls /var/lib/docker/volumes 2>/dev/null | head +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_hunt_ops_bak.sh", "wb") as f: + f.write(SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_hunt_ops_bak.sh", timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_import_exclude_both.py b/scripts/_import_exclude_both.py new file mode 100644 index 0000000..c2f36b7 --- /dev/null +++ b/scripts/_import_exclude_both.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""Import timeslot exclude from manual featured on both hosts; push catalog.""" +from __future__ import annotations + +import paramiko + +SCRIPT = r''' +import json, urllib.request, http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req, timeout=15).status) +# import-manual +req=urllib.request.Request("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude/import-manual", data=json.dumps({"merge":True}).encode(), headers={"Content-Type":"application/json"}, method="POST") +raw=op.open(req, timeout=60).read() +p=json.loads(raw) +print("import added", p.get("added"), "count", p.get("count")) +st=json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=30).read()) +print("exclude count", st.get("count"), "effective", st.get("effective_room_count"), "manual_extra", st.get("manual_featured_extra")) +# push catalog if edge +try: + req=urllib.request.Request("http://127.0.0.1:8014/api/ops/neko/push-catalog", data=b"{}", headers={"Content-Type":"application/json"}, method="POST") + print("push", op.open(req, timeout=90).read()[:400]) +except Exception as e: + print("push skip/err", type(e).__name__, e) +# live-map +lm=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=150).read()) +print("live_count", lm.get("live_count"), "source", lm.get("source")) +for k,v in sorted((lm.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", (v.get("title") or k)[:28], v.get("source")) +''' + + +def run(port, user, pwd, label, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pwd, timeout=25) + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_imp_ex.py", "w") as f: + f.write(SCRIPT) + sftp.close() + cmd = f"echo '{pwd}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_imp_ex.py" + _, o, e = c.exec_command(cmd, timeout=240) + else: + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -", timeout=240) + o.channel.sendall(SCRIPT.encode()) + o.channel.shutdown_write() + print("====", label, "====") + print(o.read().decode("utf-8", "replace")) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print(err[-600:]) + c.close() + + +if __name__ == "__main__": + run(4014, "eric", "4669805", "phys", sudo=True) + run(22, "root", "Xiao4669805", "vps") diff --git a/scripts/_insp_nomadro_live.py b/scripts/_insp_nomadro_live.py new file mode 100644 index 0000000..a20cf6c --- /dev/null +++ b/scripts/_insp_nomadro_live.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Inspect and start nomadro.live Next.js only (no WP router).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +set -e +echo '=== units ===' +systemctl cat nomadro-live-router.service 2>/dev/null | head -40 || true +systemctl cat tiktok-promo-frontend.service 2>/dev/null | head -50 || true +ls /etc/systemd/system/*promo* /etc/systemd/system/*live* 2>/dev/null || true +echo '=== caddy nomadro.live ===' +cat /etc/caddy/sites/nomadro.live.caddy 2>/dev/null || true +grep -n 'nomadro.live\|3015\|4404\|8089' /etc/caddy/Caddyfile /etc/caddy/sites/*.caddy 2>/dev/null | head -40 +echo '=== status before ===' +systemctl is-active nomadro-live-router.service tiktok-promo-frontend.service 2>/dev/null || true +ss -lntp | grep -E ':3015|:4404|:8089' || true +curl -sS -m 8 -o /dev/null -w 'public_before=%{http_code}\n' -L https://nomadro.live/ || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_insp_live.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_insp_live.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_insp_nomadro_next.py b/scripts/_insp_nomadro_next.py new file mode 100644 index 0000000..15304df --- /dev/null +++ b/scripts/_insp_nomadro_next.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Inspect nomadro Next.js unit + how traffic is routed.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +echo '=== unit files ===' +for u in nomadro-web nomadro nomadro-api nomadro-router nomadro-live-router; do + echo "---- $u ----" + systemctl cat ${u}.service 2>/dev/null | head -50 || echo missing +done +echo '=== /var/www/nomadro.com ===' +ls -la /var/www/nomadro.com | head -30 +head -40 /var/www/nomadro.com/package.json +test -d /var/www/nomadro.com/.next && echo has_next_build=yes +echo '=== caddy host nomadro.com ===' +grep -RIn --include='*.caddy' -E '^(nomadro\.com|www\.nomadro\.com)|host nomadro' /etc/caddy 2>/dev/null | head -40 +grep -RIn --include='*.caddy' 'reverse_proxy.*30[0-9][0-9]|nomadro.com' /etc/caddy/sites 2>/dev/null | head -50 +echo '=== nginx nomadro ===' +grep -RIn 'nomadro.com' /etc/nginx 2>/dev/null | head -40 +echo '=== listening ports likely next ===' +ss -lntp | grep -E 'node|next|3000|3001|3010|4000|4015' || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_insp_nomadro_next.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_insp_nomadro_next.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_inspect_seaweed_dylive.py b/scripts/_inspect_seaweed_dylive.py new file mode 100644 index 0000000..3b17563 --- /dev/null +++ b/scripts/_inspect_seaweed_dylive.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Inspect seaweed bucket prefixes + try vacuum reclaim.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r""" +set -e +while IFS= read -r line; do case "$line" in DY_S3_*=*) export "$line" ;; esac; done < <(grep -E '^Environment=DY_S3_' /etc/systemd/system/douyinweb-api.service | sed 's/^Environment=//' | tr ' ' '\n' | grep DY_S3_) +# also from show +eval $(systemctl show douyinweb-api -p Environment --value | tr ' ' '\n' | grep '^DY_S3_' | sed 's/^/export /') +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from collections import defaultdict +from app import s3_storage +from app.config import settings +client=s3_storage._client() +# list ALL keys by prefix top-level +sizes=defaultdict(lambda:[0,0]) # count, bytes +token=None +total=0 +oldest=None +newest=None +while True: + kw={'Bucket':settings.s3_bucket,'MaxKeys':1000} + if token: kw['ContinuationToken']=token + r=client.list_objects_v2(**kw) + for o in r.get('Contents') or []: + k=o['Key']; total+=1 + top=k.split('/',1)[0] if '/' in k else k + if k.startswith('covers/avatars/'): + top='covers/avatars' + elif k.startswith('covers/'): + top='covers/session' + sizes[top][0]+=1; sizes[top][1]+=int(o.get('Size') or 0) + lm=o.get('LastModified') + if lm: + ts=lm.timestamp() + oldest=ts if oldest is None or tsnewest else newest + if not r.get('IsTruncated'): break + token=r.get('NextContinuationToken') +print('total_objects', total) +import time +print('oldest_age_days', None if oldest is None else round((time.time()-oldest)/86400,2)) +print('newest_age_days', None if newest is None else round((time.time()-newest)/86400,2)) +for k,v in sorted(sizes.items(), key=lambda x:-x[1][1]): + print(f'{k}: n={v[0]} bytes={v[1]} ({v[1]/1e6:.1f}MB)') +PY +echo '---volume files---' +ls -lhS /data/seaweed/volume | head -30 +du -sh /data/seaweed/volume /data/seaweed/filer /data/seaweed/master +echo '---weed ports---' +ss -lntp | grep -E 'weed|8333|9333|18888|19333|28080' || true +echo '---vacuum via weed shell if any---' +# master port from systemd +systemctl cat douyinweb-sw-master douyinweb-sw-volume douyinweb-s3 2>/dev/null | head -80 +""" +_i, o, e = c.exec_command(cmd, timeout=120, get_pty=True) +chan = o.channel +start = time.time() +while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > 110: + print("TIMEOUT") + break + time.sleep(0.1) +print("\n[exit", chan.recv_exit_status(), "]") +c.close() diff --git a/scripts/_inv_nomadro_com.py b/scripts/_inv_nomadro_com.py new file mode 100644 index 0000000..2329a74 --- /dev/null +++ b/scripts/_inv_nomadro_com.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read-only inventory of nomadro.com related units/sites on VPS.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +echo '=== systemd units matching nomadro ===' +systemctl list-units --all --type=service --no-pager 2>/dev/null | grep -iE 'nomadro|dylive|douyin' || true +systemctl list-unit-files --no-pager 2>/dev/null | grep -iE 'nomadro|dylive' || true +echo '=== docker containers nomadro ===' +docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null | grep -iE 'nomadro|NAME' || true +echo '=== caddy sites ===' +ls -la /etc/caddy/sites 2>/dev/null | head -40 +ls -la /etc/caddy 2>/dev/null | head -20 +grep -RIl 'nomadro.com' /etc/caddy 2>/dev/null | head -20 +echo '=== processes / dirs ===' +ls -d /opt/*nomadro* /opt/*Nomadro* /home/*/nomadro* 2>/dev/null || true +ss -lntp 2>/dev/null | grep -E ':(80|443|3[0-9]{3}|4[0-9]{3}|8[0-9]{3})\s' | head -40 +echo '=== curl public ===' +curl -sS -m 8 -o /dev/null -w 'nomadro.com=%{http_code}\n' https://nomadro.com/ || true +curl -sS -m 8 -o /dev/null -w 'www.nomadro.com=%{http_code}\n' https://www.nomadro.com/ || true +curl -sS -m 8 -o /dev/null -w 'dylive=%{http_code}\n' https://dylive.nomadro.com/api/health || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_inv_nomadro.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_inv_nomadro.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_inventory_vps_services.py b/scripts/_inventory_vps_services.py new file mode 100644 index 0000000..e3c7bd5 --- /dev/null +++ b/scripts/_inventory_vps_services.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Inventory running services on dylive VPS (107.173.30.245).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def connect(): + last = None + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=60, + banner_timeout=180, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected attempt={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"retry {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(8) + raise SystemExit(f"ssh failed: {last}") + + +def run(c, cmd, timeout=120): + print(f"\n===== {cmd[:100]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return out + + +def main(): + c = connect() + try: + run(c, "uptime; free -h | head -3; df -h / | tail -1") + run(c, "systemctl list-units --type=service --state=running --no-pager --no-legend") + run(c, "docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null | head -60") + run(c, "ss -lntup | head -80") + run( + c, + "systemctl list-unit-files --type=service --state=enabled --no-pager --no-legend | " + "awk '{print $1}' | grep -Eiv '^(ssh|sshd|systemd|dbus|cron|rsyslog|network|NetworkManager|" + "ufw|fail2ban|docker|containerd|caddy|nginx|douyinweb|getty|user@|snap|multipath|" + "irqbalance|polkit|ModemManager|packagekit|unattended|chrony|ntp|qemu|serial)' | head -80", + ) + run(c, "systemctl list-units --type=service --state=running --no-pager --no-legend | awk '{print $1}'") + run(c, "ls /etc/systemd/system/douyinweb* 2>/dev/null; ls /etc/caddy 2>/dev/null; which caddy nginx 2>/dev/null") + run(c, "ps aux --sort=-%mem | head -25") + finally: + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_list_dylive_cleanup.py b/scripts/_list_dylive_cleanup.py new file mode 100644 index 0000000..ec07b50 --- /dev/null +++ b/scripts/_list_dylive_cleanup.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""List cleanup candidates on dylive — read only, no deletes.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def run(c, cmd, timeout=120): + print(f"\n===== {cmd[:100]} =====", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + print(o.read().decode("utf-8", "replace")[:20000], flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("[stderr]", err[:800], flush=True) + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(6): + try: + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + break + except Exception as ex: + print(ex, flush=True) + time.sleep(1 + i) + else: + raise SystemExit("ssh_fail") + + run(c, "df -h /; echo free=$(df -BG / | awk 'NR==2{print $4}')") + run( + c, + r""" +echo '### journal' +journalctl --disk-usage 2>/dev/null +du -sh /var/log/journal /var/log 2>/dev/null +ls -lhS /var/log/*.log /var/log/*.gz 2>/dev/null | head -15 +echo '### apt cache' +du -sh /var/cache/apt/archives 2>/dev/null +echo '### docker/containerd' +docker system df 2>/dev/null +du -sh /var/lib/docker /var/lib/containerd 2>/dev/null +docker images --format '{{.Repository}}:{{.Tag}}\t{{.Size}}\t{{.ID}}' 2>/dev/null | head -20 +docker ps -a --filter status=exited --format '{{.Names}}\t{{.Status}}\t{{.Size}}' 2>/dev/null | head -20 +echo '### douyinWEB backups/neko/clips' +du -sh /opt/douyinWEB/backend/data/backups /opt/douyinWEB/backend/data/neko /opt/douyinWEB/backend/data/clips /opt/douyinWEB/frontend/.next* 2>/dev/null +ls -lhS /opt/douyinWEB/backend/data/backups 2>/dev/null | head -20 +du -sh /opt/douyinWEB/backend/data/neko/* 2>/dev/null | sort -h | tail -15 +echo '### frontend bak' +ls -ld /opt/douyinWEB/frontend/.next* 2>/dev/null +du -sh /opt/douyinWEB/frontend/.next* 2>/dev/null +echo '### /root /tmp /data' +du -sh /root /tmp /data 2>/dev/null +du -sh /root/* /tmp/* 2>/dev/null | sort -h | tail -20 +du -sh /data/* 2>/dev/null | sort -h | tail -20 +echo '### other apps under /opt' +du -sh /opt/* 2>/dev/null | sort -h +echo '### seaweed / volume' +du -sh /opt/seaweedfs /data/seaweed* /var/lib/seaweed* 2>/dev/null +find /data /opt -maxdepth 3 -iname '*seaweed*' -o -iname '*volume*' 2>/dev/null | head -20 +echo '### old tarballs / deploys' +find /tmp /root /opt -maxdepth 2 -type f \( -name '*.tgz' -o -name '*.tar.gz' -o -name '*.zip' -o -name '*recv*' -o -name '*deploy*' \) -printf '%s %p\n' 2>/dev/null | sort -n | tail -30 +""", + ) + c.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_map_dual_vps_s3_caddy.py b/scripts/_map_dual_vps_s3_caddy.py new file mode 100644 index 0000000..27c28af --- /dev/null +++ b/scripts/_map_dual_vps_s3_caddy.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Read-only map: where dy.nomadro.live / .com Caddy and S3 live.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOSTS = [ + ("vps-dylive", "107.173.30.245"), + ("vps-dy", "108.174.50.68"), +] + + +def run(host, script, timeout=90): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + break + except Exception as e: + print(f"retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + else: + raise SystemExit(f"ssh fail {host}") + _i, o, e = c.exec_command(script, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +SCRIPT = r""" +set +e +echo '=== hostname / ips ===' +hostname -f 2>/dev/null; hostname +ip -4 addr show scope global | awk '/inet /{print $2,$NF}' +echo +echo '=== caddy present? ===' +systemctl is-active caddy 2>/dev/null +ss -lntp | grep -E ':443|:80|:8333|:28333|:8014|:4015' | head -30 +echo +echo '=== site files mentioning dy.nomadro.live / douyin-covers ===' +grep -Rnl 'dy.nomadro.live\|douyin-covers\|s3.nomadro' /etc/caddy 2>/dev/null | head -40 +for f in /etc/caddy/sites/*live* /etc/caddy/sites/dy* /etc/caddy/Caddyfile /etc/caddy/sites/s3*; do + [ -f "$f" ] || continue + echo "---- $f ----" + grep -nE 'dy\.nomadro\.(live|com)|douyin-covers|8333|28333|covers|s3\.nomadro' "$f" 2>/dev/null | head -40 +done +echo +echo '=== seaweed / s3 units ===' +systemctl is-active seaweed-s3.service douyinweb-s3.service 2>/dev/null +ls /etc/seaweedfs/ 2>/dev/null +echo +echo '=== frp-aux ===' +systemctl is-active dy-frp-http-aux.service 2>/dev/null +systemctl status dy-frp-http-aux.service --no-pager -l 2>&1 | head -25 +echo HOST_DONE +""" + +for label, host in HOSTS: + print(f"\n######## {label} {host} ########", flush=True) + print(run(host, SCRIPT), flush=True) +print("ALL_DONE", flush=True) diff --git a/scripts/_migrate_dylive_ops_data_to_dy.py b/scripts/_migrate_dylive_ops_data_to_dy.py new file mode 100644 index 0000000..855af63 --- /dev/null +++ b/scripts/_migrate_dylive_ops_data_to_dy.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +"""Migrate ops data dylive(107) → dy.nomadro.live(108): rooms, shorts, assign. + +Preserves row IDs. Does not overwrite shorts_oauth_profiles (already migrated). +Remaps neko_instance_id > 4 down into 1..4 round-robin on destination. +""" +from __future__ import annotations + +import io +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SRC = ("107.173.30.245", "root", "Xiao4669805") +DST = ("108.174.50.68", "root", "Xiao4669805") +DB = "/opt/douyinWEB/backend/data/monitor.db" + +TABLES = [ + "rooms", + "blacklist", + "channel_groups", + "shorts_channels", + "yt_long_channels", + "yt_assign_groups", + "yt_assign_pool_urls", + "yt_assign_featured_urls", + "yt_assign_slot_urls", +] + + +def connect(host, user, password): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + user, + password, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n$ {cmd[:180]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-8000:] if len(out) > 8000 else out, flush=True) + return code, out + + +# 1) Export on dylive +src = connect(*SRC) +code, _ = run( + src, + rf""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import sqlite3 +from pathlib import Path +src = sqlite3.connect("{DB}") +dst_path = Path("/tmp/dylive_ops_export.db") +if dst_path.exists(): + dst_path.unlink() +dst = sqlite3.connect(str(dst_path)) +tables = {TABLES!r} +src_tables = {{r[0] for r in src.execute("SELECT name FROM sqlite_master WHERE type='table'")}} +for t in tables: + if t not in src_tables: + print(t, "MISSING") + continue + schema = src.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,)).fetchone() + if not schema or not schema[0]: + print(t, "NO_SCHEMA") + continue + dst.execute(schema[0]) + cols = [r[1] for r in src.execute(f"PRAGMA table_info([{{t}}])")] + rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall() + if rows: + q = ",".join(["?"] * len(cols)) + csql = ",".join(f"[{{c}}]" for c in cols) + dst.executemany(f"INSERT INTO [{{t}}] ({{csql}}) VALUES ({{q}})", rows) + dst.commit() + print(t, len(rows)) +dst.close(); src.close() +print("EXPORT_OK", dst_path.stat().st_size) +PY +""", +) +assert code == 0 + +# 2) SFTP pull then push +print("[sftp] download export...", flush=True) +sftp = src.open_sftp() +sftp.get("/tmp/dylive_ops_export.db", "C:/Users/admin/AppData/Local/Temp/dylive_ops_export.db") +sftp.close() +src.close() + +dst = connect(*DST) +print("[sftp] upload export...", flush=True) +sftp = dst.open_sftp() +sftp.put("C:/Users/admin/AppData/Local/Temp/dylive_ops_export.db", "/tmp/dylive_ops_export.db") +sftp.close() + +# 3) Ensure neko capacity enough, merge tables, remap neko ids +code, _ = run( + dst, + rf""" +set -euo pipefail +cd /opt/douyinWEB/backend +set -a; source /etc/douyinweb.env; set +a +export DY_PUBLIC_BASE_URL=https://dy.nomadro.live +export DY_NEKO_NAT1TO1=108.174.50.68 + +# Grow Neko fleet to cover remapped slots (max used id after remap = 4, but create 8 for headroom) +./.venv/bin/python - <<'PY' +from app import youtube_neko as yn +print(yn.ensure_capacity(8, start_instances=set(), reconcile_running=False)) +print(yn.sync_nginx_proxy(8)) +PY +nginx -t && systemctl reload nginx + +./.venv/bin/python - <<'PY' +import sqlite3 +from pathlib import Path + +SRC = Path("/tmp/dylive_ops_export.db") +DST = Path("{DB}") +TABLES = {TABLES!r} +assert SRC.is_file() and DST.is_file() + +# Init schema on dst via app +from app import db, yt_assign_db +_ = db.list_rooms() +yt_assign_db.ensure_yt_assign_tables() + +src = sqlite3.connect(str(SRC)) +dst = sqlite3.connect(str(DST)) +src.row_factory = sqlite3.Row +dst.row_factory = sqlite3.Row + +def cols(con, table): + return [r[1] for r in con.execute(f"PRAGMA table_info([{{table}}])").fetchall()] + +def exists(con, table): + return bool(con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone()) + +report = {{}} +for t in TABLES: + if not exists(src, t): + report[t] = {{"skipped": "missing_src"}} + continue + if not exists(dst, t): + schema = src.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,)).fetchone() + if schema and schema[0]: + dst.execute(schema[0]); dst.commit() + else: + report[t] = {{"skipped": "no_schema"}} + continue + sc, dc = cols(src, t), cols(dst, t) + common = [c for c in sc if c in dc] + rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall() + before = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] + # clear destination table then insert (fresh box expected empty) + dst.execute(f"DELETE FROM [{{t}}]") + inserted = 0 + for r in rows: + d = dict(r) + # Remap oversized Neko ids into 1..8 + if t == "yt_assign_groups" and "neko_instance_id" in d: + try: + nid = int(d.get("neko_instance_id") or 0) + except Exception: + nid = 0 + if nid > 8: + d["neko_instance_id"] = ((nid - 1) % 8) + 1 + elif nid < 0: + d["neko_instance_id"] = 0 + vals = [d.get(c) for c in common] + placeholders = ",".join(["?"] * len(common)) + colnames = ",".join(f"[{{c}}]" for c in common) + dst.execute( + f"INSERT OR REPLACE INTO [{{t}}] ({{colnames}}) VALUES ({{placeholders}})", + vals, + ) + inserted += 1 + dst.commit() + after = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] + report[t] = {{"src": len(rows), "before": before, "after": after, "inserted": inserted}} + +dst.close(); src.close() +import json +print(json.dumps(report, ensure_ascii=False, indent=2)) + +# sanity via app APIs +rooms = db.list_rooms() +print("rooms_total", rooms.get("total") if isinstance(rooms, dict) else len(rooms)) +chs = db.list_shorts_channels() +print("shorts_channels", len(chs), "with_rt", sum(1 for c in chs if str(c.get("refresh_token") or "").strip())) +groups = yt_assign_db.list_groups(include_urls=False) +print("assign_groups", len(groups)) +neko_ids = sorted({{int(g.get("neko_instance_id") or 0) for g in groups}}) +print("neko_ids", neko_ids) +PY + +systemctl restart douyinweb-api douyinweb-web +sleep 4 +systemctl is-active douyinweb-api douyinweb-web +""", + t=400, +) +assert code == 0 + +# 4) Firewall for Neko HTTP + WebRTC (ufw if present; else iptables accept) +code, _ = run( + dst, + r""" +set +e +echo ===FIREWALL=== +if command -v ufw >/dev/null 2>&1; then + ufw status | head -5 + # HTTP already 80/443; open neko webrtc ranges used by compose + ufw allow 52000:52499/udp comment 'douyinweb-neko-webrtc' || true + ufw allow 52000:52499/tcp comment 'douyinweb-neko-webrtc-tcp' || true + ufw allow 52300:52320/udp comment 'douyinweb-neko-mux' || true + ufw allow 52300:52320/tcp comment 'douyinweb-neko-mux-tcp' || true + ufw status numbered | tail -20 +else + # iptables INPUT accepts for webrtc (idempotent check) + iptables -C INPUT -p udp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52000:52499 -j ACCEPT + iptables -C INPUT -p tcp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport 52000:52499 -j ACCEPT + iptables -C INPUT -p udp --dport 52300:52320 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52300:52320 -j ACCEPT + echo iptables_ok +fi + +# smoke +curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/l.json -w 'login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \ + -H 'Content-Type: application/json' -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/l.json; echo +curl -sS -b /tmp/dyj -o /tmp/rooms.json -w 'rooms_api:%{http_code}\n' 'https://dy.nomadro.live/api/rooms?limit=5' +python3 - <<'PY' +import json +d=json.load(open('/tmp/rooms.json',encoding='utf-8')) +if isinstance(d, dict): + print('rooms', d.get('total'), 'sample', len(d.get('rooms') or [])) +else: + print('rooms_raw', type(d)) +PY +curl -sS -b /tmp/dyj -o /tmp/ch.json -w 'channels:%{http_code}\n' https://dy.nomadro.live/api/shorts/channels +python3 - <<'PY' +import json +d=json.load(open('/tmp/ch.json',encoding='utf-8')) +rows=d if isinstance(d,list) else (d.get('channels') or d.get('items') or []) +print('channels', len(rows)) +print('names', [ (r.get('name') or '')[:30] for r in rows[:8] ]) +PY +curl -sS -b /tmp/dyj -o /tmp/ag.json -w 'assign:%{http_code}\n' https://dy.nomadro.live/api/youtube/assign/groups +python3 - <<'PY' +import json +d=json.load(open('/tmp/ag.json',encoding='utf-8')) +rows=d if isinstance(d,list) else (d.get('groups') or []) +print('assign', len(rows)) +print('names', [ (r.get('name') or '')[:30] for r in rows[:8] ]) +PY +""", +) + +dst.close() +print("DONE", time.strftime("%H:%M:%S"), "exit", code) +raise SystemExit(code) diff --git a/scripts/_migrate_dylive_settings_to_dy.py b/scripts/_migrate_dylive_settings_to_dy.py new file mode 100644 index 0000000..f94666e --- /dev/null +++ b/scripts/_migrate_dylive_settings_to_dy.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Copy safe settings from dylive (107) → dy.nomadro.live (108). + +Copies: OAuth client profiles (id/secret), redirect URI template, relay quality defaults. +Does NOT copy: rooms/monitor.db, refresh_tokens, assign groups, channel cards. +""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SRC = ("107.173.30.245", "root", "Xiao4669805") # dylive +DST = ("108.174.50.68", "root", "Xiao4669805") # dy.nomadro.live +DST_REDIRECT = "https://dy.nomadro.live/api/shorts/oauth/callback" + + +def connect(host, user, password): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + user, + password, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + return code, out + + +# --- pull from dylive --- +src = connect(*SRC) +code, out = run( + src, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import db +sm = db.get_settings_map() +keys = [ + 'shorts_oauth_profiles', + 'shorts_oauth_client_id', + 'shorts_oauth_client_secret', + 'shorts_oauth_redirect_uri', + 'shorts_gcp_project_id', + 'youtube_relay_quality_preset', + 'youtube_relay_bitrate', + 'youtube_relay_use_rtmps', + 'youtube_relay_exclusive_live', + 'youtube_relay_time_slot_mode', + 'neko_mem_limit', + 'dy_cookie', +] +payload = {} +for k in keys: + if k in sm and sm.get(k) not in (None, ''): + payload[k] = sm.get(k) +# redact print +safe = json.loads(json.dumps(payload)) +if isinstance(safe.get('shorts_oauth_profiles'), list): + for p in safe['shorts_oauth_profiles']: + if p.get('client_secret'): + p['client_secret'] = (p['client_secret'][:4] + '…' + p['client_secret'][-4:]) if len(str(p['client_secret']))>8 else '***' + if p.get('client_id'): + p['client_id'] = str(p['client_id'])[:28] + '…' +if safe.get('shorts_oauth_client_secret'): + s=str(safe['shorts_oauth_client_secret']); safe['shorts_oauth_client_secret']=s[:4]+'…'+s[-4:] +if safe.get('dy_cookie'): + safe['dy_cookie'] = f"len={len(str(payload.get('dy_cookie') or ''))}" +print('SUMMARY', json.dumps(safe, ensure_ascii=False)) +print('PAYLOAD_JSON_START') +print(json.dumps(payload, ensure_ascii=False)) +print('PAYLOAD_JSON_END') +# also dump client_secret files if any +from pathlib import Path +for p in Path('/opt/douyinWEB').glob('client_secret_*.json'): + print('FILE', p.name) +PY +""", +) +src.close() +print(out[-4000:]) +assert code == 0, out + +start = out.find("PAYLOAD_JSON_START") +end = out.find("PAYLOAD_JSON_END") +assert start >= 0 and end > start, "no payload" +payload = json.loads(out[start + len("PAYLOAD_JSON_START") : end].strip()) + +# Rewrite redirect to dy domain; keep profile credentials +payload["shorts_oauth_redirect_uri"] = DST_REDIRECT +# Do not enable relay automatically on empty box +payload.pop("youtube_relay_enabled", None) + +# Merge into dst +dst = connect(*DST) +sftp = dst.open_sftp() +with sftp.file("/tmp/migrate_settings.json", "w") as f: + f.write(json.dumps(payload, ensure_ascii=False)) +sftp.close() + +code2, out2 = run( + dst, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import db +from app import shorts_oauth + +payload = json.loads(open('/tmp/migrate_settings.json', encoding='utf-8').read()) +sm = db.get_settings_map() + +# Merge OAuth profiles: fill empty slots from source; never wipe existing filled secrets unless source has them +src_profiles = {p['id']: p for p in shorts_oauth.normalize_oauth_profiles(payload.get('shorts_oauth_profiles'))} +cur_profiles = shorts_oauth.normalize_oauth_profiles(sm.get('shorts_oauth_profiles')) +merged = [] +for p in cur_profiles: + row = dict(p) + sp = src_profiles.get(row['id']) or {} + if sp.get('client_id') and (not row.get('client_id') or sp.get('client_id')): + # prefer source if present + if sp.get('client_id'): + row['client_id'] = sp['client_id'] + if sp.get('client_secret'): + row['client_secret'] = sp['client_secret'] + if sp.get('label'): + row['label'] = sp['label'] + merged.append(row) +# add any missing ids from source +have = {p['id'] for p in merged} +for pid, sp in src_profiles.items(): + if pid not in have: + merged.append(sp) + +patch = { + 'shorts_oauth_profiles': merged, + 'shorts_oauth_redirect_uri': payload.get('shorts_oauth_redirect_uri') or 'https://dy.nomadro.live/api/shorts/oauth/callback', +} +for k in ( + 'shorts_oauth_client_id', 'shorts_oauth_client_secret', 'shorts_gcp_project_id', + 'youtube_relay_quality_preset', 'youtube_relay_bitrate', 'youtube_relay_use_rtmps', + 'youtube_relay_exclusive_live', 'youtube_relay_time_slot_mode', 'neko_mem_limit', + 'dy_cookie', +): + if payload.get(k) not in (None, ''): + patch[k] = payload[k] + +db.update_settings_map(patch) +sm2 = db.get_settings_map() +print('redirect', sm2.get('shorts_oauth_redirect_uri')) +print('neko_mem_limit', sm2.get('neko_mem_limit')) +print('dy_cookie_len', len(str(sm2.get('dy_cookie') or ''))) +print('relay_preset', sm2.get('youtube_relay_quality_preset'), 'bitrate', sm2.get('youtube_relay_bitrate')) +for p in shorts_oauth.normalize_oauth_profiles(sm2.get('shorts_oauth_profiles')): + cid = str(p.get('client_id') or '') + print(p['id'], 'cid', (cid[:28]+'…') if cid else '-', 'sec', bool(p.get('client_secret'))) + +# ensure nginx neko include synced for 4 instances +from app import youtube_neko as yn +print('sync_nginx', yn.sync_nginx_proxy(4)) +PY +nginx -t && systemctl reload nginx +curl -sS -o /dev/null -w 'login:%{http_code}\n' --max-time 15 https://dy.nomadro.live/login + +# copy any client_secret json files from dylive upload if present on /tmp +ls -la /opt/douyinWEB/client_secret_*.json 2>/dev/null || true +""", +) +dst.close() +print(out2[-5000:]) +print("exit", code2) +raise SystemExit(code2) diff --git a/scripts/_nuclear_stop_docker_revive.py b/scripts/_nuclear_stop_docker_revive.py new file mode 100644 index 0000000..9ce1a59 --- /dev/null +++ b/scripts/_nuclear_stop_docker_revive.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Nuclear recovery: stop Docker entirely, free RAM, start caddy+api+web+frpp+wg.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(port=22, user="root", pw="Xiao4669805", tries=12): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=40, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print(f"ssh :{port} ok {i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"ssh :{port} retry {i} {ex}", flush=True) + time.sleep(3) + raise SystemExit(f"ssh fail :{port} {last}") + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:230]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print((out[-7000:] if len(out) > 7000 else out) or f"(empty {code})", flush=True) + return code + + +v = ssh() + +# Stop docker hard — Neko cannot run on 3.8G with load 200 +run( + v, + "systemctl stop docker.socket docker containerd 2>/dev/null; " + "pkill -9 -f dockerd; pkill -9 -f containerd; pkill -9 chrome; pkill -9 chromium; " + "sleep 3; free -h | head -2; uptime; " + "ps aux | grep -E 'chrome|dockerd|neko' | grep -v grep | wc -l", + 90, +) + +# Ensure caddy timeout and start core stack WITHOUT docker +run( + v, + "mkdir -p /etc/systemd/system/caddy.service.d; " + "printf '[Service]\\nTimeoutStartSec=300\\nTimeoutStopSec=30\\n' > /etc/systemd/system/caddy.service.d/timeout.conf; " + "systemctl daemon-reload; " + "systemctl reset-failed caddy douyinweb-api douyinweb-web 2>/dev/null; " + "systemctl start seaweed-master seaweed-volume seaweed-filer seaweed-s3 frpp nginx; " + "systemctl restart douyinweb-pb douyinweb-yt; sleep 2; " + "systemctl restart douyinweb-api; sleep 6; " + "systemctl restart douyinweb-web; sleep 4; " + "systemctl restart caddy; sleep 5; " + "free -h | head -2; uptime; " + "systemctl is-active caddy nginx frpp douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "ss -lntp | grep -E ':(443|80|8014|4015|4014|8020)\\b' || true", + 300, +) + +run( + v, + "curl -sS -m 12 http://127.0.0.1:8014/api/health | head -c 300; echo; " + "curl -sS -m 12 -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/; " + "curl -sS -m 12 -o /dev/null -w 'yt=%{http_code}\\n' http://127.0.0.1:4015/youtube; " + "curl -sS -m 12 -o /dev/null -w 'caddy443=%{http_code}\\n' -k https://127.0.0.1/ -H 'Host: dylive.nomadro.com'; " + "wg-quick down wg-dy 2>/dev/null; wg-quick up wg-dy; sleep 2; wg show wg-dy | head -14", + 60, +) +v.close() + +# Physical guest via FRP +try: + g = ssh(4014, "eric", "4669805") + run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy 2>/dev/null; wg-quick up wg-dy; sleep 2; " + "systemctl start douyinweb-api douyinweb-web; " + "wg show wg-dy | head -12; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 160; echo; " + "systemctl is-active douyinweb-api douyinweb-web" + "'", + 90, + ) + g.close() +except Exception as ex: + print("guest fail", ex, flush=True) + +v = ssh() +run(v, "ping -c 3 -W 2 10.8.0.2 | tail -4; curl -sS -m 10 -o /dev/null -w 'wg_api=%{http_code}\\n' http://10.8.0.2:8014/api/health", 30) +v.close() + +print("\n=== public ===", flush=True) +with httpx.Client(follow_redirects=False, timeout=20) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/youtube", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + ]: + try: + r = cl.get(u) + print(u, r.status_code, (r.headers.get("location") or "")[:40], flush=True) + except Exception as ex: + print(u, "ERR", ex, flush=True) + +print("DONE_NUCLEAR", flush=True) diff --git a/scripts/_open_opsneko_google_login.py b/scripts/_open_opsneko_google_login.py new file mode 100644 index 0000000..b132dd0 --- /dev/null +++ b/scripts/_open_opsneko_google_login.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Open Google/YouTube Studio login pages on both ops-neko for re-auth. Do NOT touch profiles.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +set -e +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, urllib.request, urllib.error +url = "https://accounts.google.com/ServiceLogin?service=youtube&continue=https%3A%2F%2Fstudio.youtube.com%2F" +# open new tab via CDP +try: + # Prefer PUT /json/new + req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + urllib.parse.quote(url, safe=""), method="PUT") + import urllib.parse + with urllib.request.urlopen(req, timeout=8) as resp: + data = json.loads(resp.read().decode()) + print("opened", data.get("id"), data.get("url", "")[:100]) +except Exception as e1: + import urllib.parse + try: + with urllib.request.urlopen("http://127.0.0.1:9222/json/new?" + urllib.parse.quote(url, safe=""), timeout=8) as resp: + data = json.loads(resp.read().decode()) + print("opened_get", data.get("id"), data.get("url", "")[:100]) + except Exception as e2: + print("fail", e1, e2) +PY +done +""" + + +def main() -> None: + # fix SH - urllib.parse import order + sh = r""" +set -e +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + docker exec -i "$name" python3 - <<'PY' +import json, urllib.request, urllib.parse +url = "https://accounts.google.com/ServiceLogin?service=youtube&continue=https%3A%2F%2Fstudio.youtube.com%2F" +try: + req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + urllib.parse.quote(url, safe=""), method="PUT") + with urllib.request.urlopen(req, timeout=8) as resp: + data = json.loads(resp.read().decode()) + print("opened", data.get("id"), (data.get("url") or "")[:120]) +except Exception as e1: + try: + with urllib.request.urlopen("http://127.0.0.1:9222/json/new?" + urllib.parse.quote(url, safe=""), timeout=8) as resp: + data = json.loads(resp.read().decode()) + print("opened_get", data.get("id"), (data.get("url") or "")[:120]) + except Exception as e2: + print("fail", type(e1).__name__, e1, "|", type(e2).__name__, e2) +PY +done +""" + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_open_ops_login.sh", "wb") as f: + f.write(sh.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_open_ops_login.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_open_wg_udp_live.py b/scripts/_open_wg_udp_live.py new file mode 100644 index 0000000..28c597f --- /dev/null +++ b/scripts/_open_wg_udp_live.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Open UDP 51820 on VPS for wg-dy. Live flush. No Neko.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + + +def connect(): + for i in range(8): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print("connected", flush=True) + return c + except Exception as ex: + print(f"retry {i} {ex}", flush=True) + time.sleep(2) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=45): + print(f"$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print(f"→ {o.channel.recv_exit_status()}", flush=True) + + +c = connect() +run(c, "ufw status verbose 2>/dev/null | head -40; iptables -L INPUT -n | head -30; iptables -L INPUT -n | grep -E '51820|51821' || true") +run( + c, + "ufw allow 51820/udp comment 'wg-dy' 2>/dev/null || true; " + "iptables -C INPUT -p udp --dport 51820 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 51820 -j ACCEPT; " + "iptables -C INPUT -p udp --dport 51821 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 51821 -j ACCEPT; " + "echo rules_ok; " + "ufw status | grep 51820 || true; " + "iptables -L INPUT -n | grep 5182 || true", +) +c.close() + +# poke from guest +print("## guest poke", flush=True) +g = connect() +# reconnect as guest +g.close() +g = paramiko.SSHClient() +g.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +g.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, +) +print("connected :4014", flush=True) +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy; wg-quick up wg-dy; sleep 5; " + "wg show wg-dy; ping -c 4 -W 2 10.8.0.1 | tail -6" + "'", + t=50, +) +g.close() + +c = connect() +run(c, "wg show wg-dy; ping -c 3 -W 2 10.8.0.2 | tail -5; curl -sS -m 8 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health", t=35) +c.close() + +with httpx.Client(follow_redirects=False, timeout=12) as cl: + for u in ["https://dy.nomadro.com/api/health", "https://dylive.nomadro.com/api/health"]: + try: + print(u, cl.get(u).status_code, flush=True) + except Exception as ex: + print(u, ex, flush=True) +print("DONE", flush=True) diff --git a/scripts/_opsneko_tm_ext_inside.py b/scripts/_opsneko_tm_ext_inside.py new file mode 100644 index 0000000..a2c09a7 --- /dev/null +++ b/scripts/_opsneko_tm_ext_inside.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Diagnose + force re-seed Tampermonkey extension inside one ops-neko container.""" +import json +import shutil +from pathlib import Path + +EXT = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE = Path("/home/neko/.config/google-chrome/Default") +SEED = Path("/etc/neko/tampermonkey-seed/Default/Extensions") / EXT + + +def diag(tag: str) -> None: + print(f"== {tag} ==") + for pref_name in ("Preferences", "Secure Preferences"): + p = BASE / pref_name + print(pref_name, "exists", p.exists()) + if not p.exists(): + continue + try: + d = json.loads(p.read_text()) + except Exception as exc: + print(" parse_fail", exc) + continue + e = ((d.get("extensions") or {}).get("settings") or {}).get(EXT) or {} + print(" state", e.get("state"), "path", e.get("path"), "loc", e.get("location")) + print(" disable_reasons", e.get("disable_reasons")) + mf = e.get("manifest") if isinstance(e.get("manifest"), dict) else {} + print(" mf_ver", mf.get("version"), "mf_name", mf.get("name")) + root = BASE / "Extensions" / EXT + print("ext_dir", root.exists()) + if root.exists(): + for m in sorted(root.glob("*/manifest.json")): + d = json.load(open(m, encoding="utf-8")) + missing = [ + rel + for rel in ("background.html", "background.js", "extension.js") + if not (m.parent / rel).exists() + ] + print(" installed", m.parent.name, "mv", d.get("manifest_version"), "ver", d.get("version"), "missing", missing or "none") + + +def repair() -> None: + ext_dst = BASE / "Extensions" / EXT + for p in ( + ext_dst, + BASE / "Local Extension Settings" / EXT, + BASE / "Managed Extension Settings" / EXT, + ): + if p.exists(): + shutil.rmtree(p, ignore_errors=True) + print("removed", p) + if not SEED.exists(): + raise SystemExit(f"NO_SEED_MOUNT {SEED}") + (BASE / "Extensions").mkdir(parents=True, exist_ok=True) + shutil.copytree(SEED, ext_dst) + versions = sorted( + p.name for p in ext_dst.iterdir() if p.is_dir() and (p / "manifest.json").is_file() + ) + chosen = versions[-1] if versions else "" + print("seeded versions", versions, "chosen", chosen) + manifest = {} + if chosen: + manifest = json.loads((ext_dst / chosen / "manifest.json").read_text(encoding="utf-8")) + entry = { + "state": 1, + "path": f"{EXT}/{chosen}" if chosen else EXT, + "location": 4, + "manifest": manifest, + "was_installed_by_default": False, + "from_webstore": False, + } + for pref_name in ("Preferences", "Secure Preferences"): + pref = BASE / pref_name + d: dict = {} + if pref.exists(): + try: + d = json.loads(pref.read_text(encoding="utf-8")) + except Exception: + d = {} + settings = d.setdefault("extensions", {}).setdefault("settings", {}) + cur = dict(settings.get(EXT) or {}) + cur.update(entry) + cur.pop("disable_reasons", None) + settings[EXT] = cur + pref.write_text(json.dumps(d, separators=(",", ":")), encoding="utf-8") + print("patched", pref_name, cur.get("path"), "state", cur.get("state"), "disable", cur.get("disable_reasons")) + + +if __name__ == "__main__": + import sys + + mode = sys.argv[1] if len(sys.argv) > 1 else "diag" + if mode == "repair": + diag("before") + repair() + diag("after") + else: + diag("diag") diff --git a/scripts/_parse_channel_live_pages.py b/scripts/_parse_channel_live_pages.py new file mode 100644 index 0000000..97b1c80 --- /dev/null +++ b/scripts/_parse_channel_live_pages.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import json +import re +import sys +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CARDS = [ + ("asian streetfood", "UCXFErW9DeE8EXrInlnyCnVw"), + ("hackrobotlite", "UCYnwXkCMmVFf8Vr6MlWb-Jw"), + ("nomad Street Food", "UCf-uYs6f5yg3iWylnHkIKug"), + ("Nomadro Hub", "UC-8V3pDMlM2B75fvbYRBsNg"), + ("walking tour", "UC0ojQ8aKSSOse1z-FGcUKUw"), + ("nomad vlog", "UCtVfMFdLTN4ap__8g7MFtVw"), + ("asian streetfood2", "UCjQ8jnBm2N4FGRowNXcXThw"), + ("nomadvlog", "UCO9wMc9tj9mD221Gu0rLBeA"), +] + + +def fetch(url: str) -> str: + req = urllib.request.Request( + url, + headers={"User-Agent": "Mozilla/5.0", "Accept-Language": "en-US,en;q=0.9"}, + ) + with urllib.request.urlopen(req, timeout=20) as r: + return r.read().decode("utf-8", "replace") + + +def parse_live(html: str) -> dict: + out = {"is_live": False, "video_id": "", "title": ""} + # ytInitialPlayerResponse + for pat in ( + r"ytInitialPlayerResponse\s*=\s*(\{.+?\})\s*;", + r"var\s+ytInitialPlayerResponse\s*=\s*(\{.+?\})\s*;", + ): + m = re.search(pat, html, re.S) + if not m: + continue + raw = m.group(1) + # trim balanced-ish: find first { to matching via json raw_decode + try: + dec = json.JSONDecoder() + obj, _ = dec.raw_decode(html[m.start(1) :]) + except Exception: + try: + obj = json.loads(raw) + except Exception: + continue + vd = obj.get("videoDetails") or {} + out["video_id"] = str(vd.get("videoId") or "") + out["title"] = str(vd.get("title") or "")[:80] + out["is_live"] = bool(vd.get("isLive") or vd.get("isLiveContent")) + micro = ((obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}) + if micro.get("liveBroadcastDetails", {}).get("isLiveNow"): + out["is_live"] = True + break + if not out["is_live"]: + if '"isLiveNow":true' in html or '"isLive":true' in html: + out["is_live"] = True + return out + + +def main(): + live_n = 0 + for name, cid in CARDS: + url = f"https://www.youtube.com/channel/{cid}/live" + try: + html = fetch(url) + info = parse_live(html) + except Exception as ex: + print(name, "ERR", ex) + continue + if info["is_live"]: + live_n += 1 + print("LIVE", name, cid, info) + else: + print("off ", name, cid, info) + print("TOTAL_LIVE", live_n) + + +if __name__ == "__main__": + main() diff --git a/scripts/_patch_remove_slots_ui.py b/scripts/_patch_remove_slots_ui.py new file mode 100644 index 0000000..2be2c49 --- /dev/null +++ b/scripts/_patch_remove_slots_ui.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +from pathlib import Path + +p = Path(__file__).resolve().parents[1] / "frontend" / "src" / "components" / "YtAssignPanel.tsx" +lines = p.read_text(encoding="utf-8").splitlines(True) + +start = end = None +for i, L in enumerate(lines): + if "直播地址列表 · {(selected.featured || []).length}" in L: + j = i + while j > 0 and " start, (start, end) +print(f"removing lines {start+1}-{end}") +new_lines = lines[:start] + lines[end:] +text = "".join(new_lines) + +repls = [ + ( + "即分配页的精选列表;FFmpeg 推流只从此列表选源(优先在播)。从普通池点 ★ 加入。", + "关「时间段排班」且开「自动推流」时:从此列表监听开播并推流(优先在播)。单路独占时只跑最先开播的频道。从普通池点 ★ 加入。", + ), + ("从左侧普通列表点星标加入精选", "从左侧普通列表点星标加入"), + ( + 'className="order-1 rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4 lg:col-span-2 xl:order-1 xl:col-span-1"', + 'className="order-1 rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4 lg:order-1"', + ), + ( + "时间段自动选源与「全频道填充」不会选用它们,避免与已指定的手动直播撞同一路流。", + "时间段自动选源不会选用它们,避免与已指定的手动直播撞同一路流。", + ), +] +for a, b in repls: + if a not in text: + print("WARN missing:", a[:40]) + else: + text = text.replace(a, b, 1) + +# Drop unused slot helpers / Clock if safe +# Keep functions but remove slotIds memo to avoid lint — remove if unused +if "slotIds" in text and "const slotIds" in text: + # remove slotIds useMemo block + import re + + text2, n = re.subn( + r"\n const slotIds = useMemo\(\n \(\) => new Set\(\(selected\?\.slots \|\| \[\]\)\.map\(\(s\) => String\(s\.pool_url_id\)\)\),\n \[selected\]\n \);\n", + "\n", + text, + count=1, + ) + if n: + text = text2 + print("removed slotIds") + +# Remove Clock from imports if unused +if "Clock" in text and text.count("Clock") == 1: + text = text.replace(" Clock,\n", "") + print("removed Clock import") +elif "Clock" in text: + print("Clock still referenced", text.count("Clock")) + +p.write_text(text, encoding="utf-8") +print("done", len(lines), "->", len(text.splitlines())) +assert "时间段列表(轮播)" not in text +assert text.count("直播地址列表 ·") == 1 diff --git a/scripts/_pause_vps_nonproject.py b/scripts/_pause_vps_nonproject.py new file mode 100644 index 0000000..00a1f70 --- /dev/null +++ b/scripts/_pause_vps_nonproject.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Pause non-douyinWEB Docker stacks on dylive to free RAM for single Neko. + +Does NOT touch: sing-box, frpp, wg-quick, douyinweb-* containers/units. +""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + + +def run(cmd: str, t: int = 180) -> str: + print("\n=====", cmd[:100].replace("\n", " "), flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return out + + +# Inventory first +run( + r""" +set +e +echo '=== before mem ===' +free -h | head -3 +echo '=== all containers ===' +docker ps -a --format '{{.Names}}\t{{.Status}}\t{{.Image}}' | sort +echo '=== compose projects ===' +docker ps -a --format '{{.Label "com.docker.compose.project"}}\t{{.Names}}' | sort -u +""" +) + +# Stop non-douyinWEB stacks by compose project / name patterns +run( + r""" +set +e +# Protect these name prefixes +protect='douyinweb-|neko' + +stop_one() { + local name="$1" + case "$name" in + douyinweb-*|douyinweb_*) echo "KEEP $name"; return 0 ;; + esac + echo "STOP $name" + docker stop "$name" 2>/dev/null || true +} + +# Explicit known non-project stacks from prior diag +for n in \ + nomadro-live-wp-wordpress-1 nomadro-live-wp-db-1 \ + nomadro-wp-wordpress-1 nomadro-wp-db-1 \ + deploy-nsqd-1 deploy-nsqadmin-1 deploy-nsqlookupd-1 \ + ntfy-ntfy-1 \ + umami-umami-1 umami-db-1 +do + stop_one "$n" +done + +# Also stop any other running containers that are not douyinweb-* +while read -r name; do + [ -z "$name" ] && continue + stop_one "$name" +done < <(docker ps --format '{{.Names}}') + +echo '=== after stop ===' +docker ps --format '{{.Names}}\t{{.Status}}' | sort +sync; echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true +free -h | head -3 +# ensure untouchables still up +systemctl is-active sing-box.service frpp.service wg-quick@wg-dy.service 2>/dev/null || true +systemctl is-active douyinweb-api.service douyinweb-web.service 2>/dev/null || true +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +""" +) +c.close() +print("DONE") diff --git a/scripts/_post_reboot_recover.py b/scripts/_post_reboot_recover.py new file mode 100644 index 0000000..349935e --- /dev/null +++ b/scripts/_post_reboot_recover.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Post-reboot recover: core sites only. Never start Neko. Live flush.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def ssh(port=22, user="root", pw="Xiao4669805", tries=20): + last = None + for i in range(tries): + try: + print(f"ssh :{port} try={i} ...", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + port, + user, + pw, + timeout=20, + banner_timeout=30, + auth_timeout=30, + allow_agent=False, + look_for_keys=False, + ) + print(f"ssh :{port} OK", flush=True) + return c + except Exception as ex: + last = ex + print(f"ssh :{port} fail {type(ex).__name__}: {ex}", flush=True) + time.sleep(3) + raise SystemExit(f"ssh dead: {last}") + + +def run(c, cmd, t=120, label=""): + print(f"\n[{label}] $ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + # poll for output + buf = b"" + deadline = time.time() + t + while True: + if o.channel.recv_ready(): + chunk = o.channel.recv(8192) + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + chunk = o.channel.recv_stderr(8192) + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.exit_status_ready(): + # drain + while o.channel.recv_ready(): + chunk = o.channel.recv(8192) + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + while o.channel.recv_stderr_ready(): + chunk = o.channel.recv_stderr(8192) + buf += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + code = o.channel.recv_exit_status() + print(f"\n[{label}] → {code}", flush=True) + return code, buf.decode("utf-8", "replace") + if time.time() > deadline: + print(f"\n[{label}] TIMEOUT", flush=True) + return -1, buf.decode("utf-8", "replace") + time.sleep(0.15) + + +def probe(): + print("\n=== PUBLIC ===", flush=True) + with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/youtube", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code} loc={(r.headers.get('location') or '')[:40]}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + + +print("=== post-reboot recover (no neko start) ===", flush=True) +v = ssh(22) + +run(v, "uptime; free -h | head -2; hostname", 30, "host") + +# If docker came back and auto-started old containers, STOP them only — do not start any +run( + v, + "systemctl is-active docker; " + "if systemctl is-active docker >/dev/null 2>&1; then " + " docker ps --format '{{.Names}} {{.Status}}' 2>/dev/null | head -40; " + " ids=$(docker ps -q --filter name=douyinweb-neko 2>/dev/null); " + " if [ -n \"$ids\" ]; then echo STOPPING_NEKO; docker stop -t 2 $ids; fi; " + " for id in $(docker ps -q --filter name=douyinweb-neko -a 2>/dev/null); do " + " docker update --restart=no $id >/dev/null 2>&1 || true; " + " done; " + "fi; " + "free -h | head -2", + 90, + "neko-stop-only", +) + +# Core services +run( + v, + "systemctl start seaweed-master seaweed-volume seaweed-filer seaweed-s3 frpp nginx caddy " + "douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web 'wg-quick@wg-dy' 2>&1; " + "sleep 3; " + "systemctl is-active caddy nginx frpp douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb docker; " + "ss -lntp | grep -E ':(443|80|8014|4015|4014|8020)\\b' || true; " + "free -h | head -2; uptime", + 120, + "start-core", +) + +run( + v, + "curl -sS -m 12 http://127.0.0.1:8014/api/health | head -c 300; echo; " + "curl -sS -m 10 -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/; " + "curl -sS -m 10 -o /dev/null -w 'yt=%{http_code}\\n' http://127.0.0.1:4015/youtube; " + "curl -sS -m 10 -o /dev/null -w 'caddy=%{http_code}\\n' -k -H 'Host: dylive.nomadro.com' https://127.0.0.1/api/health; " + "wg show wg-dy | head -14", + 50, + "local", +) +v.close() + +# Physical guest +try: + g = ssh(4014, "eric", "4669805") + run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick up wg-dy 2>/dev/null || wg-quick down wg-dy; wg-quick up wg-dy; " + "systemctl start douyinweb-api douyinweb-web; sleep 2; " + "wg show wg-dy | head -12; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 180; echo" + "'", + 90, + "guest", + ) + g.close() +except Exception as ex: + print(f"guest skip: {ex}", flush=True) + +v = ssh(22) +run( + v, + "ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 10 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health", + 30, + "tunnel", +) +v.close() + +probe() +print("DONE", flush=True) diff --git a/scripts/_post_reboot_steps.py b/scripts/_post_reboot_steps.py new file mode 100644 index 0000000..960aaed --- /dev/null +++ b/scripts/_post_reboot_steps.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Short-step post-reboot recover. Reconnect every command. No Neko start.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def connect(port=22, user="root", pw="Xiao4669805"): + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + port, + user, + pw, + timeout=25, + banner_timeout=40, + auth_timeout=25, + allow_agent=False, + look_for_keys=False, + ) + print(f" connected :{port}", flush=True) + return c + except Exception as ex: + print(f" connect fail {i}: {ex}", flush=True) + time.sleep(2) + raise RuntimeError("cannot connect") + + +def step(title: str, cmd: str, t: int = 60, port=22, user="root", pw="Xiao4669805"): + print(f"\n## {title}", flush=True) + print(f"$ {cmd[:180]}", flush=True) + c = connect(port, user, pw) + try: + _i, o, e = c.exec_command(cmd, timeout=t) + out = b"" + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + chunk = o.channel.recv(4096) + out += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + chunk = o.channel.recv_stderr(4096) + out += chunk + sys.stdout.write(chunk.decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + rest = o.read() + e.read() + if rest: + sys.stdout.write(rest.decode("utf-8", "replace")) + sys.stdout.flush() + code = o.channel.recv_exit_status() + print(f"→ {code}", flush=True) + return code + finally: + c.close() + + +# Wait a bit for boot settle +print("boot settle 8s...", flush=True) +time.sleep(8) + +step("uptime", "uptime; free -h | head -2") +step( + "disable docker autostart neko restart policy + stop running neko", + "systemctl stop docker.socket 2>/dev/null; " + "systemctl start docker; sleep 2; " + "docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' || true; " + "for c in $(docker ps -aq --filter name=douyinweb-neko); do docker update --restart=no $c; docker stop -t 1 $c; done; " + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' || echo no_running_neko; " + "free -h | head -2", + t=90, +) + +step("start seaweed+frpp+nginx", "systemctl start seaweed-master seaweed-volume seaweed-filer seaweed-s3 frpp nginx; systemctl is-active seaweed-s3 frpp nginx") +step("start douyinweb", "systemctl start douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web; sleep 4; systemctl is-active douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb") +step("start caddy+wg", "systemctl start caddy 'wg-quick@wg-dy'; sleep 2; systemctl is-active caddy; wg show wg-dy | head -10 || true") +step( + "listen+health", + "ss -lntp | grep -E ':(443|80|8014|4015|4014)\\b' || true; " + "curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 250; echo; " + "curl -sS -m 8 -o /dev/null -w 'web=%{http_code} yt=' http://127.0.0.1:4015/; " + "curl -sS -m 8 -o /dev/null -w '%{http_code}\\n' http://127.0.0.1:4015/youtube; " + "curl -sS -m 8 -o /dev/null -w 'caddy=%{http_code}\\n' -k -H 'Host: dylive.nomadro.com' https://127.0.0.1/api/health", + t=50, +) + +print("\n## guest FRP", flush=True) +try: + step( + "guest wg+api", + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick up wg-dy 2>/dev/null || (wg-quick down wg-dy; wg-quick up wg-dy); " + "systemctl start douyinweb-api douyinweb-web; sleep 2; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 160; echo; " + "wg show wg-dy | head -10'", + t=80, + port=4014, + user="eric", + pw="4669805", + ) +except Exception as ex: + print(f"guest fail: {ex}", flush=True) + +step( + "tunnel", + "ping -c 2 -W 2 10.8.0.2 | tail -3; curl -sS -m 8 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health", + t=25, +) + +print("\n=== PUBLIC ===", flush=True) +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/youtube", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_probe_all_assign_live.py b/scripts/_probe_all_assign_live.py new file mode 100644 index 0000000..fcf8552 --- /dev/null +++ b/scripts/_probe_all_assign_live.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +"""Probe both asian UCs + live-map via HTTP API (no DB write).""" +from __future__ import annotations + +import json +import paramiko + +REMOTE = r''' +import json, os, re, urllib.request, socket, sqlite3 + +def fetch(url, proxy=""): + handlers=[] + if proxy: + handlers.append(urllib.request.ProxyHandler({"http":proxy,"https":proxy})) + opener=urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + req=urllib.request.Request(url, headers={ + "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", + "Accept-Language":"en-US,en;q=0.9", + }) + html=opener.open(req, timeout=28).read().decode("utf-8","ignore") + return html + +def analyze(html): + out={} + out["len"]=len(html) + out["isLiveNow_re"]=bool(re.search(r'"isLiveNow"\s*:\s*true', html, re.I)) + out["isLive_re"]=bool(re.search(r'"isLive"\s*:\s*true', html, re.I)) + out["LIVE_badge"]=('"style":"LIVE"' in html) or ('"text":"LIVE"' in html) + m=re.search(r'rel="canonical" href="([^"]+)"', html) + out["canonical"]=m.group(1) if m else "" + m=re.search(r'property="og:url" content="([^"]+)"', html) + out["og"]=m.group(1) if m else "" + m=re.search(r'ytInitialPlayerResponse\s*=\s*', html) + if m: + try: + obj,_=json.JSONDecoder().raw_decode(html[m.end():]) + vd=obj.get("videoDetails") or {} + micro=((obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}) + out["player"]={ + "videoId": vd.get("videoId"), + "title": (vd.get("title") or "")[:80], + "isLive": vd.get("isLive"), + "isLiveContent": vd.get("isLiveContent"), + "liveBroadcastDetails": micro.get("liveBroadcastDetails"), + } + except Exception as e: + out["player_err"]=str(e)[:120] + else: + out["player"]=None + m2=re.search(r'ytInitialData\s*=\s*', html) + if m2: + try: + obj,_=json.JSONDecoder().raw_decode(html[m2.end():]) + s=json.dumps(obj) + out["initialData_isLiveNow"]=('"isLiveNow": true' in s) or ('"isLiveNow":true' in s) + vids=re.findall(r'"videoId":"([A-Za-z0-9_-]{11})".{0,500}?"style":"LIVE"', s) + if not vids: + vids=re.findall(r'"style":"LIVE".{0,500}?"videoId":"([A-Za-z0-9_-]{11})"', s) + out["live_video_ids"]=vids[:8] + except Exception as e: + out["initial_err"]=str(e)[:120] + return out + +proxy="" +s=socket.socket(); s.settimeout(0.4) +try: + s.connect(("127.0.0.1",7890)); proxy="http://127.0.0.1:7890" +except Exception: + proxy="" +finally: + s.close() +print("proxy", proxy or "direct") + +targets=[ + ("asian_UCXF", "UCXFErW9DeE8EXrInlnyCnVw"), + ("asian_UCjQ", "UCjQ8jnBm2N4FGRowNXcXThw"), + ("hack", "UCYnwXkCMmVFf8Vr6MlWb-Jw"), + ("nomadSF", "UCf-uYs6f5yg3iWylnHkIKug"), + ("hub", "UC-8V3pDMlM2B75fvbYRBsNg"), + ("vlog", "UCtVfMFdLTN4ap__8g7MFtVw"), + ("nomadvlog", "UCO9wMc9tj9mD221Gu0rLBeA"), + ("walk", "UC0ojQ8aKSSOse1z-FGcUKUw"), +] +for name,cid in targets: + url="https://www.youtube.com/channel/%s/live" % cid + try: + html=fetch(url, proxy) + a=analyze(html) + print("---", name, cid) + print(json.dumps(a, ensure_ascii=False)[:1000]) + except Exception as e: + print("---", name, cid, "ERR", type(e).__name__, str(e)[:160]) + +# public live-map via local API +print("=== api live-map ===") +try: + raw=urllib.request.urlopen("http://127.0.0.1:8014/api/youtube/live-map", timeout=60).read() + p=json.loads(raw) + print("live_count", p.get("live_count"), "source", p.get("source"), "checked", p.get("checked_at")) + for k,v in (p.get("entries") or {}).items(): + if v.get("is_live"): + print(" LIVE", k, v.get("source"), (v.get("title") or "")[:40], (v.get("live_url") or "")[:90]) +except Exception as e: + print("api ERR", e) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=200) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + out = stdout.read().decode("utf-8", "replace") + print(out) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-800:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys") diff --git a/scripts/_probe_android_live.py b/scripts/_probe_android_live.py new file mode 100644 index 0000000..4719749 --- /dev/null +++ b/scripts/_probe_android_live.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +"""Android/TV Innertube player — bypass WEB bot wall for live check.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, urllib.request, socket, re + +proxy="" +s=socket.socket(); s.settimeout(0.4) +try: + s.connect(("127.0.0.1",7890)); proxy="http://127.0.0.1:7890" +except Exception: + proxy="" +finally: + s.close() + +def opener(px): + handlers=[] + if px: + handlers.append(urllib.request.ProxyHandler({"http":px,"https":px})) + return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + +CLIENTS={ + "WEB": {"clientName":"WEB","clientVersion":"2.20250301.00.00","hl":"en","gl":"US"}, + "ANDROID": {"clientName":"ANDROID","clientVersion":"19.28.35","androidSdkVersion":30,"hl":"en","gl":"US"}, + "TVHTML5": {"clientName":"TVHTML5_SIMPLY_EMBEDDED_PLAYER","clientVersion":"2.0","hl":"en","gl":"US"}, + "IOS": {"clientName":"IOS","clientVersion":"19.29.1","deviceModel":"iPhone14,3","hl":"en","gl":"US"}, +} + +def player(vid, client_key): + ctx={"client":CLIENTS[client_key]} + body=json.dumps({"context":ctx,"videoId":vid}).encode() + # api key for android often needed; try without first + url="https://www.youtube.com/youtubei/v1/player?prettyPrint=false" + if client_key=="ANDROID": + url="https://youtubei.googleapis.com/youtubei/v1/player?key=AIzaSyA8eiZmM1FaDVz_Vx_WRwVIgm1QAo7Lrm4&prettyPrint=false" + req=urllib.request.Request(url, data=body, headers={ + "Content-Type":"application/json", + "User-Agent":"com.google.android.youtube/19.28.35 (Linux; U; Android 11) gzip" if client_key=="ANDROID" else "Mozilla/5.0", + "X-YouTube-Client-Name":"3" if client_key=="ANDROID" else "1", + "X-YouTube-Client-Version":CLIENTS[client_key]["clientVersion"], + }, method="POST") + raw=opener(proxy).open(req, timeout=25).read().decode("utf-8","ignore") + obj=json.loads(raw) + vd=obj.get("videoDetails") or {} + mf=((obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}) + play=obj.get("playabilityStatus") or {} + return { + "title": (vd.get("title") or "")[:50], + "author": (vd.get("author") or "")[:30], + "cid": vd.get("channelId"), + "isLive": vd.get("isLive"), + "isLiveContent": vd.get("isLiveContent"), + "liveNow": (mf.get("liveBroadcastDetails") or {}).get("isLiveNow"), + "status": play.get("status"), + "reason": (play.get("reason") or "")[:60], + } + +vids={ + "asian_PF16":"PF16pG4VmSk", + "asian_1cQY":"1cQY6jHytxQ", + "hack_XW":"XW-3kA3XdfI", + "nomad_zbla":"zblaCyR1AY8", + "nomad_aG0z":"aG0zIkmCJ2E", + "vlog_L1sF":"L1sF_kZvzIk", +} +print("proxy", proxy or "direct") +for name,vid in vids.items(): + for ck in ["ANDROID","WEB"]: + try: + r=player(vid, ck) + print(name, vid, ck, json.dumps(r, ensure_ascii=False)) + except Exception as e: + print(name, vid, ck, "ERR", type(e).__name__, str(e)[:120]) + +# browse channel for live via android +print("--- android browse ---") +for cid in ["UCXFErW9DeE8EXrInlnyCnVw","UCjQ8jnBm2N4FGRowNXcXThw","UCYnwXkCMmVFf8Vr6MlWb-Jw","UCf-uYs6f5yg3iWylnHkIKug"]: + body=json.dumps({ + "context":{"client":CLIENTS["ANDROID"]}, + "browseId":cid, + "params":"EgZzZXR0aW5ncw%3D%3D" + }).encode() + # live tab params from yt: EgdzZXR0aW5ncw%3D%3D is settings; live is often EgJwaQ%3D%3D or similar + # try resolve /live via get_transcript no - use search + try: + # use player for channel live redirect via webpage android + url="https://m.youtube.com/channel/%s/live" % cid + req=urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 Mobile Safari/537.36","Accept-Language":"en-US"}) + html=opener(proxy).open(req, timeout=25).read().decode("utf-8","ignore") + now=bool(re.search(r'"isLiveNow"\s*:\s*true', html, re.I)) + live=bool(re.search(r'"isLive"\s*:\s*true', html, re.I)) + status="" + m=re.search(r'"status"\s*:\s*"([A-Z_]+)"', html) + if m: status=m.group(1) + # extract videoId near player + vid="" + m=re.search(r'ytInitialPlayerResponse\s*=\s*', html) + if m: + try: + obj,_=json.JSONDecoder().raw_decode(html[m.end():]) + vd=obj.get("videoDetails") or {} + vid=vd.get("videoId") or "" + now=bool((obj.get("microformat") or {}).get("playerMicroformatRenderer",{}).get("liveBroadcastDetails",{}).get("isLiveNow")) or now + play=(obj.get("playabilityStatus") or {}).get("status") + print(cid[:12], "m.live", "vid", vid, "isLiveNow", now, "isLive_re", live, "play", play, "title", (vd.get("title") or "")[:40]) + continue + except Exception as e: + print(cid[:12], "parse", e) + print(cid[:12], "m.live", "no_player", "isLiveNow", now, "isLive", live, "status", status, "len", len(html), "canon", (re.search(r'rel="canonical" href="([^"]+)"', html) or type("x",(object,),{"group":lambda s,i:""})()).group(1)[:60]) + except Exception as e: + print(cid[:12], "ERR", e) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=180) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-600:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") diff --git a/scripts/_probe_asian_http_live.py b/scripts/_probe_asian_http_live.py new file mode 100644 index 0000000..13db12d --- /dev/null +++ b/scripts/_probe_asian_http_live.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +"""RO probe: channel /live HTML isLiveNow on VPS + physical.""" +import paramiko + +SCRIPT = r""" +import urllib.request, re, json, os +ids=[ + ('asian','UCXFErW9DeE8EXrInlnyCnVw'), + ('hack','UCYnwXkCMmVFf8Vr6MlWb-Jw'), + ('nomadSF','UCf-uYs6f5yg3iWylnHkIKug'), +] +proxies=[None,'http://127.0.0.1:7890'] +for name,cid in ids: + for px in proxies: + url='https://www.youtube.com/channel/%s/live' % cid + try: + handlers=[] + if px: + handlers.append(urllib.request.ProxyHandler({'http':px,'https':px})) + opener=urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + req=urllib.request.Request(url, headers={ + 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Accept-Language':'en-US,en;q=0.9', + }) + html=opener.open(req, timeout=25).read().decode('utf-8','ignore') + live_now=bool(re.search(r'"isLiveNow"\s*:\s*true', html, re.I)) + is_live=bool(re.search(r'"isLive"\s*:\s*true', html, re.I)) + vid=None + m=re.search(r'ytInitialPlayerResponse\s*=\s*', html) + if m: + try: + obj,_=json.JSONDecoder().raw_decode(html[m.end():]) + vd=obj.get('videoDetails') if isinstance(obj,dict) else {} + if isinstance(vd,dict): + vid=vd.get('videoId') + print(name, 'px', px or 'direct', 'len', len(html), 'vd.isLive', vd.get('isLive'), 'vd.isLiveContent', vd.get('isLiveContent'), 'vid', vid, 're.isLiveNow', live_now) + continue + except Exception as e: + print(name, 'px', px or 'direct', 'parse_err', e, 're.isLiveNow', live_now) + continue + print(name, 'px', px or 'direct', 'len', len(html), 'no_player', 're.isLiveNow', live_now, 're.isLive', is_live, 'consent', ('consent' in html.lower()[:2000])) + except Exception as e: + print(name, 'px', px or 'direct', 'ERR', type(e).__name__, str(e)[:120]) +""" + + +def run(port: int, user: str, pwd: str, label: str) -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=20) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=120) + stdin.write(SCRIPT) + stdin.channel.shutdown_write() + print("====", label, "====") + print(stdout.read().decode()) + err = stderr.read().decode() + if err.strip(): + print("STDERR", err[-800:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys") diff --git a/scripts/_probe_asian_streams_tab.py b/scripts/_probe_asian_streams_tab.py new file mode 100644 index 0000000..91c0886 --- /dev/null +++ b/scripts/_probe_asian_streams_tab.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +"""Find LIVE badges / video ids in asian channel HTML; try innertube browse.""" +from __future__ import annotations + +import json +import paramiko + +REMOTE = r''' +import json, re, urllib.request, socket + +proxy="" +s=socket.socket(); s.settimeout(0.4) +try: + s.connect(("127.0.0.1",7890)); proxy="http://127.0.0.1:7890" +except Exception: + proxy="" +finally: + s.close() + +def opener(px): + handlers=[] + if px: + handlers.append(urllib.request.ProxyHandler({"http":px,"https":px})) + return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + +def get(url): + req=urllib.request.Request(url, headers={ + "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", + "Accept-Language":"en-US,en;q=0.9", + }) + return opener(proxy).open(req, timeout=28).read().decode("utf-8","ignore") + +for cid in ["UCXFErW9DeE8EXrInlnyCnVw","UCjQ8jnBm2N4FGRowNXcXThw"]: + for path in ["/live","/streams","/videos"]: + url="https://www.youtube.com/channel/%s%s" % (cid, path) + try: + html=get(url) + except Exception as e: + print(cid, path, "ERR", e) + continue + # count LIVE style + n_live=html.count('"style":"LIVE"') + # nearby videoIds + idxs=[m.start() for m in re.finditer(r'"style":"LIVE"', html)] + vids=[] + for i in idxs[:10]: + chunk=html[max(0,i-800):i+800] + vm=re.search(r'"videoId":"([A-Za-z0-9_-]{11})"', chunk) + if vm: vids.append(vm.group(1)) + # also BADGE_LABEL_TYPE_LIVE_NOW + n_badge=html.count("LIVE_NOW") + html.count("BADGE_LABEL_TYPE_LIVE") + print(cid[:12], path, "len", len(html), "styleLIVE", n_live, "LIVE_NOW", n_badge, "vids", vids[:6]) + +# innertube player for known live vids if any from hack +print("--- innertube player check nomad/hack ---") +for vid in ["zblaCyR1AY8","XW-3kA3XdfI"]: + body=json.dumps({ + "context":{"client":{"clientName":"WEB","clientVersion":"2.20240101.00.00","hl":"en","gl":"US"}}, + "videoId":vid + }).encode() + req=urllib.request.Request( + "https://www.youtube.com/youtubei/v1/player?prettyPrint=false", + data=body, + headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0","X-YouTube-Client-Name":"1","X-YouTube-Client-Version":"2.20240101.00.00"}, + method="POST", + ) + try: + raw=opener(proxy).open(req, timeout=20).read().decode("utf-8","ignore") + obj=json.loads(raw) + vd=obj.get("videoDetails") or {} + print(vid, "isLive", vd.get("isLive"), "isLiveContent", vd.get("isLiveContent"), "title", (vd.get("title") or "")[:50]) + mf=((obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}) + print(" liveBroadcastDetails", mf.get("liveBroadcastDetails")) + except Exception as e: + print(vid, "ERR", e) + +# youtube-svc batch +print("--- youtube-svc ---") +payload=json.dumps({"urls":[ + "https://www.youtube.com/channel/UCXFErW9DeE8EXrInlnyCnVw", + "https://www.youtube.com/channel/UCjQ8jnBm2N4FGRowNXcXThw", + "https://www.youtube.com/channel/UCYnwXkCMmVFf8Vr6MlWb-Jw", + "https://www.youtube.com/channel/UCf-uYs6f5yg3iWylnHkIKug", +]}).encode() +for port in [3101,3100,3010]: + try: + req=urllib.request.Request("http://127.0.0.1:%d/batch/live" % port, data=payload, headers={"Content-Type":"application/json"}, method="POST") + raw=urllib.request.urlopen(req, timeout=90).read().decode() + print("port", port, raw[:1500]) + break + except Exception as e: + print("port", port, "ERR", e) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=180) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-600:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") diff --git a/scripts/_probe_cn_opsneko_edge.py b/scripts/_probe_cn_opsneko_edge.py new file mode 100644 index 0000000..5162f9e --- /dev/null +++ b/scripts/_probe_cn_opsneko_edge.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe Tencent nginx for /ops-neko and current DNAT ranges.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("82.157.112.245", 22, "ubuntu", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_i, o, e = c.exec_command( + r""" +CONF=/www/server/panel/vhost/nginx/dy.nomadro.cn.conf +echo '=== nginx ops/neko ===' +sudo grep -nE 'ops-neko|/neko/|proxy_pass|location' "$CONF" | head -80 +echo '=== iptables NEKO ===' +sudo iptables -t nat -S PREROUTING | grep -i neko +echo '=== forward ===' +sudo iptables -S FORWARD | grep -E '52300|62300|62500|10.9.0.2' | head -30 +echo '=== ufw ===' +sudo ufw status | grep -E '52300|62300|62500' | head -20 +echo '=== curl slash ===' +curl -sSI -m 10 https://dy.nomadro.cn/ops-neko/1/ 2>&1 | head -20 +curl -sSI -m 10 https://dy.nomadro.cn/ops-neko/1 2>&1 | head -15 +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_cover_obj.py b/scripts/_probe_cover_obj.py new file mode 100644 index 0000000..207cbe1 --- /dev/null +++ b/scripts/_probe_cover_obj.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# physical: list weed / find real cover file for a session +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +_i, o, e = p.exec_command( + """ +echo '4669805' | sudo -S -p '' bash -lc ' +SID=b14839d6-5108-4ee0-9b32-10134c40e8e4 +curl -sS -m 8 -o /dev/null -w "local_url=%{http_code}\\n" "http://127.0.0.1:8333/douyin-covers/covers/${SID}.jpg" +curl -sS -m 8 -o /dev/null -w "local_bare=%{http_code}\\n" "http://127.0.0.1:8333/covers/${SID}.jpg" +curl -sS -m 8 -o /dev/null -w "local_root=%{http_code}\\n" "http://127.0.0.1:8333/douyin-covers/" +# weed list if awscli +which weed || true +ls /opt/douyinWEB/backend/data/covers/${SID}.jpg 2>/dev/null && echo has_local_file || echo no_local_file +# sample from disk +ls /opt/douyinWEB/backend/data/covers/ 2>/dev/null | head -3 +' +""", + timeout=50, +) +print("PHYS", (o.read() + e.read()).decode("utf-8", "replace")) +p.close() + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_i, o, e = v.exec_command( + r""" +SID=b14839d6-5108-4ee0-9b32-10134c40e8e4 +curl -sS -m 10 -o /dev/null -w "frp_covers=%{http_code} size=%{size_download}\n" "http://127.0.0.1:28333/douyin-covers/covers/${SID}.jpg" +curl -sS -m 10 -o /dev/null -w "frp_bare=%{http_code}\n" "http://127.0.0.1:28333/covers/${SID}.jpg" +curl -sS -m 10 -D- -o /dev/null "http://127.0.0.1:28333/douyin-covers/" | head -20 +# public +curl -sS -m 10 -o /dev/null -w "pub=%{http_code} size=%{size_download}\n" "https://dy.nomadro.com/douyin-covers/covers/${SID}.jpg" +# how caddy routes +grep -n 'douyin-covers\|28333\|ops-neko' /etc/caddy/sites/dy.nomadro.com.caddy | head -40 +# check aux tunnels +systemctl cat dy-frp-http-aux.service 2>/dev/null | head -80 +""", + timeout=60, +) +print("VPS", (o.read() + e.read()).decode("utf-8", "replace")) +v.close() diff --git a/scripts/_probe_cover_urls_now.py b/scripts/_probe_cover_urls_now.py new file mode 100644 index 0000000..4883948 --- /dev/null +++ b/scripts/_probe_cover_urls_now.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# physical: find a cover path +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +cmd = r'''echo 4669805 | sudo -S -p '' python3 - <<"PY" +import sqlite3, json, re +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +# any url-like cover in sessions +cols=[r[1] for r in c.execute("pragma table_info(sessions)")] +print("session_cols", [x for x in cols if "cover" in x.lower()]) +for col in cols: + if "cover" in col.lower(): + rows=c.execute(f"select id, {col} from sessions where {col} is not null and {col}!='' limit 5").fetchall() + print(col, rows[:5]) +# kv s3 +for k,v in c.execute("select key,value from kv_settings where key like '%s3%' or key like '%S3%' or key like '%cover%'").fetchall(): + print("kv", k, str(v)[:120]) +c.close() +PY''' +_i,o,e=p.exec_command(cmd, timeout=40) +print("PHYS", (o.read()+e.read()).decode("utf-8","replace")) +p.close() + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +cmd2 = r''' +set +e +# list a few objects via weed http if possible +curl -sS -m 8 'http://127.0.0.1:28333/' | head -c 200; echo +# try common path from physical public base +python3 - <<"PY" +import sqlite3 +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +cols=[r[1] for r in c.execute("pragma table_info(sessions)")] +print("dylive cover cols", [x for x in cols if "cover" in x.lower()]) +for col in cols: + if "cover" in col.lower(): + rows=c.execute(f"select id, {col} from sessions where {col}!='' limit 3").fetchall() + print(col, rows) +c.close() +PY +# probe jpg if we find one in covers local path +ls /opt/douyinWEB/backend/data/covers 2>/dev/null | head -5 +curl -sS -m 10 -o /dev/null -w 'dy_cover_root=%{http_code}\n' https://dy.nomadro.com/douyin-covers/ +curl -sS -m 10 -o /dev/null -w 'dylive_cover_root=%{http_code}\n' https://dylive.nomadro.com/douyin-covers/ +curl -sS -m 10 -o /dev/null -w 'opsneko=%{http_code}\n' https://dy.nomadro.com/ops-neko/1/ +''' +_i,o,e=v.exec_command(cmd2, timeout=60) +print("VPS", (o.read()+e.read()).decode("utf-8","replace")) +v.close() diff --git a/scripts/_probe_cover_urls_now2.py b/scripts/_probe_cover_urls_now2.py new file mode 100644 index 0000000..6a07dfc --- /dev/null +++ b/scripts/_probe_cover_urls_now2.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = p.open_sftp() +with sftp.open("/tmp/cov.py", "w") as f: + f.write( + """ +import sqlite3 +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +cols=[r[1] for r in c.execute("pragma table_info(sessions)")] +print("cols",[x for x in cols if "cover" in x.lower()]) +for col in [x for x in cols if "cover" in x.lower()]: + rows=c.execute(f"select id, substr({col},1,140) from sessions where {col}!='' order by rowid desc limit 5").fetchall() + print(col, rows) +c.close() +""" + ) +sftp.close() +_i, o, e = p.exec_command("echo '4669805' | sudo -S -p '' python3 /tmp/cov.py", timeout=40) +print("PHYS", (o.read() + e.read()).decode("utf-8", "replace")) +p.close() + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_i, o, e = v.exec_command( + r""" +python3 - <<"PY" +import sqlite3 +c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +rows=c.execute("select id, substr(cover_path,1,160) from sessions where cover_path!='' order by rowid desc limit 8").fetchall() +for r in rows: + print(r) +n=c.execute("select count(*) from sessions where cover_path like 'C:%'").fetchone()[0] +print("bad_windows_paths", n) +n2=c.execute("select count(*) from sessions where cover_path like 'http%'").fetchone()[0] +print("http_paths", n2) +c.close() +PY +SID=$(python3 -c "import sqlite3;c=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db');print(c.execute(\"select id from sessions where cover_path!='' order by rowid desc limit 1\").fetchone()[0])") +echo SID=$SID +curl -sS -m 10 -o /dev/null -w "api_cover=%{http_code} ctype=%{content_type}\n" "http://127.0.0.1:8014/api/sessions/$SID/cover" +curl -sS -m 10 -o /dev/null -w "phys_s3_obj=%{http_code}\n" "http://127.0.0.1:28333/douyin-covers/covers/${SID}.jpg" +curl -sS -m 10 -o /dev/null -w "public_dy_obj=%{http_code}\n" "https://dy.nomadro.com/douyin-covers/covers/${SID}.jpg" +curl -sS -m 10 -o /dev/null -w "opsneko=%{http_code}\n" "https://dy.nomadro.com/ops-neko/1/" +curl -sS -m 10 -o /dev/null -w "covers_root=%{http_code}\n" "https://dy.nomadro.com/douyin-covers/" +""", + timeout=60, +) +print("VPS", (o.read() + e.read()).decode("utf-8", "replace")) +v.close() diff --git a/scripts/_probe_dy_postinstall.py b/scripts/_probe_dy_postinstall.py new file mode 100644 index 0000000..197ede2 --- /dev/null +++ b/scripts/_probe_dy_postinstall.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Post-install gap check on dy.nomadro.live (108.174.50.68).""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + cmd = r""" +set +e +echo ===UNITS=== +systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-yt douyinweb-s3 douyinweb-sw-master +echo ===DOCKER=== +docker --version 2>/dev/null || echo NO_DOCKER +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' 2>/dev/null | head +echo ===HEALTH=== +curl -fsS http://127.0.0.1:8014/api/health 2>/dev/null | head -c 500; echo +echo ===LOGIN=== +curl -sS -o /tmp/login.json -w '%{http_code}' -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}'; echo +cat /tmp/login.json; echo +echo ===SETTINGS_OAUTH=== +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +import json +sm = db.get_settings_map() +keys = sorted(k for k in sm if 'oauth' in k.lower() or 'neko' in k.lower() or 'relay' in k.lower() or 'shorts' in k.lower()) +print('interesting_keys', keys[:80]) +for k in ('shorts_oauth_profiles','youtube_relay_enabled','neko_mem_limit','dy_cookie'): + v = sm.get(k) + if isinstance(v, (dict, list)): + print(k, json.dumps(v, ensure_ascii=False)[:300]) + else: + s = str(v or '') + if 'cookie' in k or 'secret' in k or 'token' in k: + print(k, f'len={len(s)}') + else: + print(k, s[:120]) +# channels / assign +try: + ch = db.list_shorts_channels() + print('shorts_channels', len(ch)) +except Exception as e: + print('shorts_err', e) +try: + from app import yt_assign_db + print('assign_groups', len(yt_assign_db.list_groups(include_urls=False))) +except Exception as e: + print('assign_err', e) +rooms = db.list_rooms() +if isinstance(rooms, dict): + print('rooms_total', rooms.get('total'), 'n', len(rooms.get('rooms') or [])) +else: + print('rooms_raw', type(rooms), len(rooms) if hasattr(rooms,'__len__') else rooms) +PY +echo ===LEFTOVER_SECRETS=== +ls -la /root/*client_secret* /opt/*client_secret* /tmp/*client_secret* 2>/dev/null | head +find /root /var/backups /opt -name 'client_secret*.json' 2>/dev/null | head +echo ===NEKO_ASSETS=== +ls /opt/douyinWEB/backend/neko/browser-launch.sh /opt/douyinWEB/backend/neko/tampermonkey-seed 2>/dev/null | head +""" + _i, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_dylive_room_live.py b/scripts/_probe_dylive_room_live.py new file mode 100644 index 0000000..19991cf --- /dev/null +++ b/scripts/_probe_dylive_room_live.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe room 369511597884 live status on VPS vs monitor badge.""" +import json +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +cd /opt/douyinWEB/backend || cd /root/douyinWEB/backend || true +python3 - <<'PY' +import json, sqlite3 +from pathlib import Path + +# find monitor.db +cands = list(Path('/opt/douyinWEB').rglob('monitor.db')) + list(Path('/root').rglob('monitor.db')) if Path('/root').exists() else list(Path('/opt/douyinWEB').rglob('monitor.db')) +print('dbs', [str(p) for p in cands[:5]]) +db = None +for p in cands: + if 'douyinWEB' in str(p) and 'backend' in str(p): + db = p; break +if not db and cands: + db = cands[0] +print('using', db) + +room = '369511597884' +con = sqlite3.connect(f'file:{db}?mode=ro', uri=True) +con.row_factory = sqlite3.Row +cur = con.cursor() +cur.execute("select room_id, url, note, last_status, last_anchor, last_title, last_checked_at, last_error from rooms where room_id=? or url like ?", (room, f'%{room}%')) +rows = [dict(r) for r in cur.fetchall()] +print('monitor_rooms', json.dumps(rows, ensure_ascii=False, default=str)) + +# live probe via app +import sys +sys.path.insert(0, str(Path(db).resolve().parents[1] / 'app') if False else '/opt/douyinWEB/backend') +sys.path.insert(0, '/opt/douyinWEB/backend') +try: + from app import douyin + r = douyin.probe_live(f'https://live.douyin.com/{room}') + print('probe', json.dumps({k:r.get(k) for k in ('ok','is_live','status','status_code','anchor','title','error','risk') if k in r or True}, ensure_ascii=False, default=str)[:800]) + print('probe_keys', sorted(r.keys())[:30]) + print('is_live', r.get('is_live'), 'status_code', r.get('status_code') or r.get('status')) +except Exception as e: + print('probe_err', type(e).__name__, e) + +# relay state for nomadvlog +cur.execute("select name from sqlite_master where type='table' and name like '%relay%'") +print('relay_tables', [r[0] for r in cur.fetchall()]) +try: + cur.execute("select group_id, status, source_url, detail, updated_at from yt_relay_states") + for row in cur.fetchall(): + d = dict(row) if hasattr(row, 'keys') else None + if d is None: + print(row) + else: + print('state', json.dumps(d, ensure_ascii=False, default=str)[:300]) +except Exception as e: + print('states_err', e) +con.close() +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + # VPS direct + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_room_live.sh", "wb") as f: + f.write(SH.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_probe_room_live.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_dylive_room_live2.py b/scripts/_probe_dylive_room_live2.py new file mode 100644 index 0000000..d9764dc --- /dev/null +++ b/scripts/_probe_dylive_room_live2.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r""" +python3 <<'PY' +import json, sqlite3, sys +from pathlib import Path +sys.path.insert(0, "/opt/douyinWEB/backend") +room = "369511597884" +db = Path("/opt/douyinWEB/backend/data/monitor.db") +con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) +con.row_factory = sqlite3.Row +cur = con.cursor() +cur.execute( + "select room_id, url, note, last_status, last_anchor, last_checked_at, last_error from rooms where room_id=? or url like ?", + (room, f"%{room}%"), +) +print("monitor", [dict(r) for r in cur.fetchall()]) +try: + cur.execute("select group_id, status, source_url, updated_at from yt_relay_states where group_id like '%' ") + rows = cur.fetchall() + print("relay_states_n", len(rows)) + for r in rows: + d = dict(r) + if "369511597884" in str(d.get("source_url") or "") or d.get("status") in ("waiting", "pushing", "running"): + print("state", d) +except Exception as e: + print("state_err", e) +con.close() + +from app import douyin +r = douyin.probe_live(f"https://live.douyin.com/{room}") +print("probe_ok", r.get("ok"), "is_live", r.get("is_live"), "status_code", r.get("status_code"), "status", r.get("status")) +print("anchor", r.get("anchor") or r.get("nickname")) +print("error", r.get("error")) +print("risk", r.get("risk") or r.get("risk_control")) +PY +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_room.sh", "wb") as f: + f.write(REMOTE.encode()) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_probe_room.sh", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_edge_catalog_studio.py b/scripts/_probe_edge_catalog_studio.py new file mode 100644 index 0000000..216123b --- /dev/null +++ b/scripts/_probe_edge_catalog_studio.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Check edge catalog studio payload + hub relay thread state.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def run(host, port, user, pwd, cmd, t=60): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pwd, timeout=25, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +def main(): + print("=== EDGE: studio snap for ops:1 + catalog dry ===") + print( + run( + *PHYS, + r"""cd /opt/douyinWEB/backend && python3 - <<'PY' +import time, json +from app import youtube_neko as yn +from app import ops_neko +from app import ops_neko_db + +print('peer', ops_neko_db.peer_status()) +# memory refs on edge +refs=sorted((yn._studio_latest_by_ref or {}).keys()) +print('edge_memory_refs', refs) +for k in refs: + if 'ops' in k or k in ('1','ops:1','ops-1'): + ev=yn._studio_latest_by_ref[k] + age=time.time()-float(ev.get('received_at') or 0) + p=ev.get('payload') if isinstance(ev.get('payload'),dict) else {} + print(' ', k, 'age', round(age,1), 'status', p.get('live_status'), 'url', str(p.get('url') or '')[:80]) + +snap=yn.studio_snapshot_for_ref('ops:1', max_age_sec=180) +print('edge_snap_ops1', json.dumps({k:snap.get(k) for k in ('live_page_open','on_air','live_status','url','age_sec','received_at','detect_source')}, ensure_ascii=False)) + +# What would catalog send? +studio=snap if (snap.get('received_at') or snap.get('on_air') or snap.get('live_page_open')) else None +print('catalog_would_send_studio', studio is not None) +if studio: + print(' keys', list(studio.keys())[:20]) +PY""", + 50, + ) + ) + + print("=== VPS: relay state + recent journal for group ===") + print( + run( + *VPS, + r"""cd /opt/douyinWEB/backend && python3 - <<'PY' +import sqlite3, time, json +con=sqlite3.connect('data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +row=con.execute('select * from yt_relay_states where group_id=?',(gid,)).fetchone() +d=dict(row) if row else {} +print('status', d.get('status'), 'error', d.get('error'), 'ffmpeg', d.get('ffmpeg_pid'), 'updated_age', round(time.time()-float(d.get('updated_at') or 0),1)) +log=str(d.get('recent_log') or '') +print('--- last 30 log lines ---') +print('\n'.join(log.strip().splitlines()[-30:])) +# sample age ops:1 +s=con.execute("select ts, live_page_open, on_air, live_status from yt_studio_samples where neko_ref='ops:1' order by ts desc limit 1").fetchone() +if s: + print('hub_db_ops1_age', round(time.time()-float(s['ts']),1), 'open', s['live_page_open'], 'on_air', s['on_air'], 'st', s['live_status']) +PY +journalctl -u douyinweb-api --since '5 min ago' --no-pager 2>/dev/null | grep -iE 'relay|ffmpeg|ops.neko|3fb8|streetfood|wait|ready|gate|invalid' | tail -40 +""", + 50, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_frp_neko_ports.py b/scripts/_probe_frp_neko_ports.py new file mode 100644 index 0000000..a3591f7 --- /dev/null +++ b/scripts/_probe_frp_neko_ports.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + allow_agent=False, + look_for_keys=False, +) +_i, o, e = c.exec_command( + r""" +set +e +echo '=== frp-aux unit ===' +cat /etc/systemd/system/dy-frp-http-aux.service +echo '=== dy.caddy neko 1-8 ===' +grep -nE 'handle_path /neko/[1-8]/|reverse_proxy .*:92' /etc/caddy/sites/dy.nomadro.com.caddy | head -50 +echo '=== dylive env neko ===' +systemctl show douyinweb-api -p Environment --value | tr ' ' '\n' | grep -E 'DY_NEKO|DY_PUBLIC|DY_INSTALL' | head +echo '=== public ip ===' +curl -sS -m 5 https://ifconfig.me; echo +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_hub_ops1_gate.py b/scripts/_probe_hub_ops1_gate.py new file mode 100644 index 0000000..bfb2182 --- /dev/null +++ b/scripts/_probe_hub_ops1_gate.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe in-memory ops:1 snapshot + wait_group_ready on VPS.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +cd /opt/douyinWEB/backend || exit 1 +python3 <<'PY' +import time, json +from app import youtube_neko as yn +from app import yt_assign_db + +# memory keys +refs=list(getattr(yn,'_studio_latest_by_ref',{}) or {}) +print('memory_refs', refs[:20], 'count', len(refs)) +for k in ('ops:1','ops-1','ops:2'): + ev=(yn._studio_latest_by_ref or {}).get(k) + if not ev: + print(k, 'MISSING') + continue + age=time.time()-float(ev.get('received_at') or 0) + p=ev.get('payload') if isinstance(ev.get('payload'),dict) else {} + print(k, 'age', round(age,1), 'status', p.get('live_status'), 'url', str(p.get('url') or '')[:70], 'signals', p.get('signals')) + +snap=yn.studio_snapshot_for_ref('ops:1', max_age_sec=120) +print('snap_ops1', {k:snap.get(k) for k in ('live_page_open','on_air','live_status','url','age_sec','detect_source','neko_ref')}) + +g=yt_assign_db.get_group('3fb8cbf7-2180-45bc-99f0-836169f0bf97') +print('group', {k:g.get(k) for k in ('name','neko_open_prefer','ops_neko_slot','ops_neko_open_url','neko_enabled','neko_instance_id')}) +gsnap=yn.studio_snapshot_for_group(g, max_age_sec=120) +print('group_snap', {k:gsnap.get(k) for k in ('live_page_open','on_air','live_status','url','age_sec','ui_source','neko_ref')}) + +# dry wait briefly +t0=time.time() +out=yn.wait_group_ready_for_live(g, timeout_sec=8.0, settle_sec=2.0, strict=True) +print('wait_out', {k:out.get(k) for k in out if k!='nudge'}, 'elapsed', round(time.time()-t0,1)) +PY +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + # Must run inside API process memory — separate python won't share memory! + # Instead hit a debug path or read catalog handler by simulating ingest from latest DB sample. + # Check how catalog ingest works + last catalog body. + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_mem_wrong.sh", "w") as f: + f.write( + r"""#!/bin/bash +# Separate process cannot see API memory. Check edge catalog payload shape + re-ingest from DB sample. +cd /opt/douyinWEB/backend +python3 <<'PY' +import sqlite3, time, json +from app import youtube_neko as yn +from app import yt_assign_db + +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +row=con.execute("select * from yt_studio_samples where neko_ref='ops:1' order by ts desc limit 1").fetchone() +d=dict(row) if row else {} +print('db_latest', {k:d.get(k) for k in ('ts','live_page_open','on_air','live_status','studio_url','neko_ref')}) +# Simulate what hub catalog should ingest +studio={ + 'live_page_open': bool(d.get('live_page_open')), + 'on_air': bool(d.get('on_air')), + 'live_status': d.get('live_status') or '', + 'url': d.get('studio_url') or '', + 'health': d.get('health') or '', + 'viewer_count': d.get('viewer_count'), + 'received_at': float(d.get('ts') or time.time()), + 'detect_source': 'db_replay', +} +print('replay_studio', studio) +out=yn.ingest_remote_studio_mirror(1, studio) +print('ingest', out) +snap=yn.studio_snapshot_for_ref('ops:1', max_age_sec=180) +print('snap_after', {k:snap.get(k) for k in ('live_page_open','on_air','live_status','url','age_sec')}) +g=yt_assign_db.get_group('3fb8cbf7-2180-45bc-99f0-836169f0bf97') +out=yn.wait_group_ready_for_live(g, timeout_sec=6.0, settle_sec=1.5, strict=True) +print('wait', out) +PY +""" + ) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_probe_mem_wrong.sh", timeout=45) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_mem_hotplug_blocks.py b/scripts/_probe_mem_hotplug_blocks.py new file mode 100644 index 0000000..e505497 --- /dev/null +++ b/scripts/_probe_mem_hotplug_blocks.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read-only: virtio-mem / hotplug memory block online status.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +echo '=== free ===' +free -h +echo '=== meminfo ===' +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo +echo '=== block size ===' +cat /sys/devices/system/memory/block_size_bytes +BS=$(cat /sys/devices/system/memory/block_size_bytes) +echo "block_size_mb=$((BS/1024/1024))" +echo '=== online/offline counts ===' +on=0; off=0 +for s in /sys/devices/system/memory/memory*/state; do + st=$(cat "$s" 2>/dev/null) + if [ "$st" = online ]; then on=$((on+1)); elif [ "$st" = offline ]; then off=$((off+1)); fi +done +echo "online_blocks=$on offline_blocks=$off" +echo "online_gb=$(echo "scale=2; $on*$BS/1024/1024/1024" | bc 2>/dev/null || python3 -c "print(round($on*$BS/1024/1024/1024,2))")" +echo "offline_gb=$(echo "scale=2; $off*$BS/1024/1024/1024" | bc 2>/dev/null || python3 -c "print(round($off*$BS/1024/1024/1024,2))")" +echo '=== balloon ===' +ls -la /sys/bus/virtio/drivers/virtio_balloon/*/ 2>/dev/null | head -20 +for f in /sys/bus/virtio/drivers/virtio_balloon/*/balloon_eff_kb /sys/devices/virtual/misc/*/balloon*; do + [ -e "$f" ] && echo "$f=$(cat $f 2>/dev/null)" +done +find /sys -path '*virtio*balloon*' -name '*' 2>/dev/null | head -40 +echo '=== guest agent ===' +systemctl is-active qemu-guest-agent 2>/dev/null || true +dpkg -l qemu-guest-agent 2>/dev/null | tail -1 || true +echo '=== memhotplug kernel ===' +lsmod | grep -iE 'balloon|memhot|virtio_mem' || true +grep -i memory /proc/cmdline || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_memblocks_ro.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_memblocks_ro.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_probe_mem_oom_guard.py b/scripts/_probe_mem_oom_guard.py new file mode 100644 index 0000000..3edd13e --- /dev/null +++ b/scripts/_probe_mem_oom_guard.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Probe memory pressure on dylive (read-only).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=60): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + print((o.read() + e.read()).decode("utf-8", "replace")[-14000:], flush=True) + return o.channel.recv_exit_status() + + +c = ssh() +run( + c, + r""" +set +e +echo ===MEM=== +free -h +swapon --show +df -h / /swapfile 2>/dev/null | head -5 +echo ===TOP=== +ps -eo pid,user,rss,oom_score_adj,comm --sort=-rss | head -30 +echo ===SLICES=== +systemctl status douyinweb-api.service --no-pager -l 2>/dev/null | head -20 +systemctl show douyinweb-api.service -p MemoryCurrent -p MemoryMax -p OOMScoreAdjust 2>/dev/null +echo ===NEKO=== +docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}} lim={{.MemPerc}}' $(docker ps -q --filter name=douyinweb-neko) +docker inspect douyinweb-neko-7 --format 'Mem={{.HostConfig.Memory}} OOMScoreAdj={{.HostConfig.OomScoreAdj}} OOMKilled={{.State.OOMKilled}}' +echo ===SERVICES_RSS=== +for u in douyinweb-api douyinweb-web pocketbase seaweed-filer seaweed-volume umami; do + systemctl is-active $u.service 2>/dev/null && systemctl show $u.service -p MemoryCurrent -p NRestarts 2>/dev/null | tr '\n' ' ' + echo " $u" +done +echo ===BROWSER_LAUNCH_FLAGS=== +grep -nE 'renderer-process|memory|disable-dev-shm|js-flags|process-per' /opt/douyinWEB/backend/neko/browser-launch.sh 2>/dev/null | head -40 +ls -la /swapfile /swapfile2 /var/swap* 2>/dev/null +""", +) +c.close() diff --git a/scripts/_probe_neko12_http.py b/scripts/_probe_neko12_http.py new file mode 100644 index 0000000..f58d5ae --- /dev/null +++ b/scripts/_probe_neko12_http.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +import paramiko + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_, o, e = c.exec_command( + "curl -sS -o /dev/null -w '%{http_code}\\n' --connect-timeout 2 http://127.0.0.1:9211/; " + "curl -sS -o /dev/null -w 'follow:%{http_code}\\n' --connect-timeout 2 -L http://127.0.0.1:9211/; " + "curl -sS -m 8 -o /dev/null -w 'https:%{http_code}\\n' https://dylive.nomadro.com/neko/12/; " + "docker inspect douyinweb-neko-12 --format '{{.State.Status}} {{.State.Health.Status}} {{json .NetworkSettings.Ports}}'", + timeout=30, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_neko3_les.py b/scripts/_probe_neko3_les.py new file mode 100644 index 0000000..fd9909c --- /dev/null +++ b/scripts/_probe_neko3_les.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +N=douyinweb-neko-3 +echo === LES Auto Dismiss strings === +docker exec "$N" bash -lc 'grep -a -o "YouTube Studio Auto Dismiss" "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/"* 2>/dev/null | head' +docker exec "$N" bash -lc 'grep -a -c "YouTube Studio Auto Dismiss" "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log" 2>/dev/null; ls -la "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/"' +echo === seed LES === +docker exec "$N" bash -lc 'ls -la /etc/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/ 2>&1; grep -a -c "YouTube Studio Auto Dismiss" /etc/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/* 2>/dev/null | head' +echo === host seed LES === +ls -la /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/ 2>&1 | head +grep -a -c "YouTube Studio Auto Dismiss" /opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/* 2>/dev/null | head +echo === provisioning http === +docker exec "$N" bash -lc 'curl -sS -m 3 http://127.0.0.1:18080/tampermonkey-provisioning.json | head -c 200; echo; curl -sS -m 3 -o /dev/null -w "%{http_code}" http://127.0.0.1:18080/youtube-studio-auto-dismiss.user.js; echo' +echo === compare neko-7 LES === +docker exec douyinweb-neko-7 bash -lc 'grep -a -c "YouTube Studio Auto Dismiss" "/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/"* 2>/dev/null | head; supervisorctl status google-chrome' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_les.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_probe_les.sh", + timeout=90, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_neko3_mounts.py b/scripts/_probe_neko3_mounts.py new file mode 100644 index 0000000..b719fff --- /dev/null +++ b/scripts/_probe_neko3_mounts.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = """#!/bin/bash +echo '=== mounts neko-3 ===' +docker inspect douyinweb-neko-3 --format '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}}{{println}}{{end}}' +echo '=== hostconfig ===' +docker inspect douyinweb-neko-3 --format 'Memory={{.HostConfig.Memory}} ShmSize={{.HostConfig.ShmSize}}' +echo '=== data dirs ===' +ls -la /opt/douyinWEB/backend/neko/ 2>/dev/null | head -25 +ls /opt/douyinWEB/backend/neko/profiles 2>/dev/null | head -20 +ls /opt/douyinWEB/data/neko 2>/dev/null | head -20 +echo '=== mem now ===' +free -h +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_neko3_m.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_probe_neko3_m.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_probe_neko3_tm_cdp.py b/scripts/_probe_neko3_tm_cdp.py new file mode 100644 index 0000000..63b483e --- /dev/null +++ b/scripts/_probe_neko3_tm_cdp.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PROBE = r''' +import json, os, urllib.request +from pathlib import Path + +print("=== chrome/main procs ===") +for pid in sorted(os.listdir("/proc"), key=lambda x: int(x) if x.isdigit() else -1): + if not pid.isdigit(): + continue + try: + raw = open(f"/proc/{pid}/cmdline", "rb").read() + except Exception: + continue + if not raw: + continue + low = raw.lower() + if b"chrome" not in low and b"browser-launch" not in low: + continue + if b"--type=" in raw: + continue + cmd = raw.replace(b"\0", b" ").decode("utf-8", "replace") + print(f"PID {pid}: {cmd[:700]}") + for part in raw.split(b"\0"): + if b"load-extension" in part or b"disable-extensions" in part: + print(" EXTFLAG", part.decode()) + +print("=== CDP ===") +try: + tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as e: + print("cdp_err", e) + tabs = [] +print("tabs", len(tabs)) +for t in tabs: + u = t.get("url") or "" + ty = t.get("type") or "" + title = (t.get("title") or "")[:60] + if ty == "service_worker" or "chrome-extension" in u or "dhdgff" in u or ty == "background_page": + print(ty, title, u[:160]) + +ext = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +pref = Path("/home/neko/.config/google-chrome/Default/Preferences") +d = json.loads(pref.read_text()) +e = ((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("=== TM prefs ===") +print("state", e.get("state"), "location", e.get("location"), "path", e.get("path")) +print("disable", e.get("disable_reasons"), "from_webstore", e.get("from_webstore")) +les = Path(f"/home/neko/.config/google-chrome/Default/Local Extension Settings/{ext}") +print("LES exists", les.exists(), "files", list(les.iterdir())[:8] if les.exists() else None) +pex = Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}") +print("profile ext dir", list(pex.iterdir()) if pex.exists() else None) +''' + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + # Write probe on host, pipe into container python via stdin + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_neko3_tm.py", "w") as f: + f.write(PROBE) + sftp.close() + cmd = ( + "echo '4669805' | sudo -S -p '' bash -lc " + "'docker exec -i douyinweb-neko-3 python3 - < /tmp/_probe_neko3_tm.py'" + ) + _i, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_neko3_tm_scripts.py b/scripts/_probe_neko3_tm_scripts.py new file mode 100644 index 0000000..65c0246 --- /dev/null +++ b/scripts/_probe_neko3_tm_scripts.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PROBE = r''' +import json, os, urllib.request, time +from pathlib import Path + +# dual chrome? +mains=[] +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw: + mains.append(pid) +print("chrome_mains", mains) + +# LES size / seed LES +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +les=Path(f"/home/neko/.config/google-chrome/Default/Local Extension Settings/{ext}") +seed=Path(f"/etc/neko/tampermonkey-seed/Default/Local Extension Settings/{ext}") +print("LES bytes", sum(p.stat().st_size for p in les.glob("*") if p.is_file()) if les.exists() else 0) +print("seed LES", list(seed.iterdir()) if seed.exists() else None) +print("seed LES bytes", sum(p.stat().st_size for p in seed.glob("*") if p.is_file()) if seed.exists() else 0) + +# provisioning scripts on disk +prov=Path("/var/www/provisioning") +print("prov files", sorted(p.name for p in prov.iterdir()) if prov.exists() else None) +for p in sorted(prov.glob("*.user.js")) if prov.exists() else []: + print(" userscript", p.name, p.stat().st_size) + +# CDP: ask TM SW for storage keys via Runtime +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) +sw=[t for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")] +print("tm_sw", len(sw), sw[0].get("webSocketDebuggerUrl") if sw else None) + +# list all pages urls +for t in tabs: + print("TAB", t.get("type"), (t.get("url") or "")[:140]) + +# Try chrome.management via evaluating in an extension page +off=[t for t in tabs if "offscreen.html" in (t.get("url") or "")] +target = (sw or off or [None])[0] +if not target: + print("no tm target") +else: + # Use /json/new to open options and dump script count via page + try: + newp = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/new?chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/options.html#nav=dashboard", timeout=5).read()) + print("opened options", newp.get("id"), newp.get("url")) + time.sleep(2) + except Exception as e: + print("open options err", e) + newp=None + tabs2=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read()) + for t in tabs2: + u=t.get("url") or "" + if "options.html" in u or "dashboard" in u: + print("OPT", t.get("title"), u[:160]) +''' + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_neko3_tm2.py", "w") as f: + f.write(PROBE) + sftp.close() + cmd = ( + "echo '4669805' | sudo -S -p '' bash -lc " + "'docker exec -i douyinweb-neko-3 python3 - < /tmp/_probe_neko3_tm2.py'" + ) + _i, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_neko7_now.py b/scripts/_probe_neko7_now.py new file mode 100644 index 0000000..6836403 --- /dev/null +++ b/scripts/_probe_neko7_now.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + +cmd = r''' +set -euo pipefail +echo '=== curl cdp ===' +docker exec douyinweb-neko-7 curl -fsS --max-time 5 http://127.0.0.1:9222/json/list | python3 -c ' +import sys,json +tabs=json.load(sys.stdin) +print("count", len(tabs)) +for t in tabs: + print(t.get("type"), "|", (t.get("title") or "")[:60], "|", (t.get("url") or "")[:140]) +' +echo '=== assign which group is neko 7 ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db, db, youtube_relay_db +for g in yt_assign_db.list_groups(include_urls=False): + if int(g.get("neko_instance_id") or 0)==7: + st=youtube_relay_db.get_relay_state(g["id"]) or {} + print(dict(name=g.get("name"), id=g.get("id"), channel_pk=g.get("channel_pk"), + category=g.get("category"), prefer=g.get("neko_open_prefer"), + relay=st.get("status"), src=st.get("source_url"))) +cfg=db.get_settings_map() +print("relay_enabled", cfg.get("youtube_relay_enabled"), + "test", cfg.get("youtube_relay_timeslot_test"), + "test_gid", cfg.get("youtube_relay_timeslot_test_group_id")) +PY +echo '=== ffmpeg ===' +ps aux | grep -i ffmpeg | grep -v grep | head -5 || true +''' +_, o, e = c.exec_command(cmd, timeout=60) +print((o.read()+e.read()).decode("utf-8","replace")) +c.close() diff --git a/scripts/_probe_neko8_eval.py b/scripts/_probe_neko8_eval.py new file mode 100644 index 0000000..9de90db --- /dev/null +++ b/scripts/_probe_neko8_eval.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +"""Probe neko8 page title via CDP Runtime.evaluate (detect Aw Snap / SIGILL).""" +from __future__ import annotations + +import base64 +import json +import os +import socket +import struct +import sys + +import paramiko + +HOST = "108.174.50.68" +PASS = "Xiao4669805" +CID = "douyinweb-neko-8" + + +def ws_connect(url: str) -> socket.socket: + assert url.startswith("ws://"), url + hostport, path = url[5:].split("/", 1) + path = "/" + path + host, port_s = hostport.split(":") + port = int(port_s) + key = base64.b64encode(os.urandom(16)).decode() + sock = socket.create_connection((host, port), timeout=8) + req = ( + f"GET {path} HTTP/1.1\r\n" + f"Host: {hostport}\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\n" + "Sec-WebSocket-Version: 13\r\n" + "\r\n" + ).encode() + sock.sendall(req) + buf = b"" + while b"\r\n\r\n" not in buf: + chunk = sock.recv(4096) + if not chunk: + raise RuntimeError("ws handshake closed") + buf += chunk + return sock + + +def ws_send(sock: socket.socket, payload: dict) -> None: + data = json.dumps(payload).encode() + mask = os.urandom(4) + header = bytearray([0x81]) + n = len(data) + if n < 126: + header.append(0x80 | n) + elif n < 65536: + header.append(0x80 | 126) + header.extend(struct.pack("!H", n)) + else: + header.append(0x80 | 127) + header.extend(struct.pack("!Q", n)) + header.extend(mask) + masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) + sock.sendall(bytes(header) + masked) + + +def ws_recv(sock: socket.socket): + def readexact(n: int) -> bytes: + out = b"" + while len(out) < n: + chunk = sock.recv(n - len(out)) + if not chunk: + raise RuntimeError("ws closed") + out += chunk + return out + + hdr = readexact(2) + b1, b2 = hdr[0], hdr[1] + opcode = b1 & 0x0F + masked = (b2 & 0x80) != 0 + ln = b2 & 0x7F + if ln == 126: + ln = struct.unpack("!H", readexact(2))[0] + elif ln == 127: + ln = struct.unpack("!Q", readexact(8))[0] + mask = readexact(4) if masked else b"" + data = readexact(ln) + if masked: + data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) + if opcode == 0x8: + return None + if opcode != 0x1: + return ws_recv(sock) + return json.loads(data.decode()) + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + + # Port-forward CDP via docker exec python inside host using host network? Use SSH tunnel to container IP. + _, o, e = c.exec_command( + f"docker inspect -f '{{{{.NetworkSettings.IPAddress}}}}' {CID}", timeout=20 + ) + ip = (o.read() + e.read()).decode().strip() + print("ip", ip) + if not ip: + print("no ip") + return 1 + + # List tabs from inside container + _, o, e = c.exec_command( + f"""docker exec {CID} python3 -c 'import json,urllib.request; print(json.dumps(json.load(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=4))))'""", + timeout=30, + ) + raw = (o.read() + e.read()).decode().strip() + tabs = json.loads(raw) + pages = [t for t in tabs if t.get("type") == "page"] + print("pages", len(pages)) + for t in pages: + print("meta", t.get("title"), (t.get("url") or "")[:90]) + + # Open SSH local forward isn't trivial; evaluate INSIDE container with a tiny python ws client. + eval_script = r''' +import base64,json,os,socket,struct,urllib.request,sys +expr = r"""(() => ({ + title: document.title || '', + href: location.href || '', + body: (document.body && (document.body.innerText || '')).slice(0, 400), + crash: !!(document.documentElement && /Aw,\s*Snap|SIGILL|STATUS_INVALID|Something went wrong/i.test(document.title + ' ' + (document.body && document.body.innerText || ''))) +}))()""" +tabs=json.load(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4)) +pages=[t for t in tabs if t.get('type')=='page'] +if not pages: + print(json.dumps({'ok':False,'err':'no page'})); sys.exit(0) + +def ws_connect(url): + hostport,path=url[5:].split('/',1); path='/'+path + host,port=hostport.split(':'); port=int(port) + key=base64.b64encode(os.urandom(16)).decode() + s=socket.create_connection((host,port),timeout=8) + s.sendall(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()) + buf=b'' + while b'\r\n\r\n' not in buf: + c=s.recv(4096) + if not c: raise RuntimeError('hs') + buf+=c + return s + +def ws_send(s,payload): + data=json.dumps(payload).encode(); mask=os.urandom(4) + h=bytearray([0x81]); n=len(data) + if n<126: h.append(0x80|n) + elif n<65536: h.append(0x80|126); h.extend(struct.pack('!H',n)) + else: h.append(0x80|127); h.extend(struct.pack('!Q',n)) + h.extend(mask); s.sendall(bytes(h)+bytes(b^mask[i%4] for i,b in enumerate(data))) + +def ws_recv(s): + def ex(n): + o=b'' + while len(o)/dev/null | tail -20\"", + timeout=30, + ) + print("=== log hits ===") + print((o.read() + e.read()).decode() or "(none)") + c.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/_probe_neko8_tabs_sigill.py b/scripts/_probe_neko8_tabs_sigill.py new file mode 100644 index 0000000..ccd9162 --- /dev/null +++ b/scripts/_probe_neko8_tabs_sigill.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe neko8 tabs/logs on dy; strengthen auto-heal detection.""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +HOST, PASS = "108.174.50.68", "Xiao4669805" + + +def connect(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + return c + + +def run(c, cmd, t=90): + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +c = connect() +print( + run( + c, + r""" +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +from app import youtube_neko +import json +tabs = youtube_neko._cdp_fetch_tabs(8) +print("tabs_n", len(tabs)) +for t in tabs[:12]: + print("TAB", json.dumps({k:t.get(k) for k in ("title","url","type","id") if k in t}, ensure_ascii=False)[:220]) +print("crash", youtube_neko._chrome_tab_crash_reason(8)) +print("cdp", youtube_neko._devtools_version_ok(8)) +PY +echo "=== chrome logs ===" +docker exec douyinweb-neko-8 bash -lc 'tail -n 120 /var/log/neko/google-chrome.log 2>/dev/null | grep -iE "SIGILL|Aw, Snap|Illegal|FATAL|crash" | tail -30' +docker exec douyinweb-neko-8 bash -lc 'ls -la /var/log/neko/ 2>/dev/null | head' +""", + 60, + ), + flush=True, +) +c.close() diff --git a/scripts/_probe_neko_mem.py b/scripts/_probe_neko_mem.py new file mode 100644 index 0000000..cd81f80 --- /dev/null +++ b/scripts/_probe_neko_mem.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +import paramiko + +REMOTE = r'''#!/bin/bash +echo '=== host mem ===' +free -h +echo +echo '=== neko containers mem ===' +docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.CPUPerc}}' $(docker ps -q --filter name=douyinweb-neko) 2>/dev/null | head -40 +echo +echo '=== neko12 limits ===' +docker inspect douyinweb-neko-12 --format 'Memory={{.HostConfig.Memory}} MemorySwap={{.HostConfig.MemorySwap}} NanoCPUs={{.HostConfig.NanoCpus}} ShmSize={{.HostConfig.ShmSize}} OomKillDisable={{.HostConfig.OomKillDisable}}' +echo +echo '=== neko12 env footprint knobs ===' +docker inspect douyinweb-neko-12 --format '{{range .Config.Env}}{{println .}}{{end}}' | grep -iE 'MEM|FPS|SCREEN|BITRATE|SHM|RENDER|MAX' +echo +echo '=== chrome procs in neko12 ===' +docker exec douyinweb-neko-12 sh -c 'ps -eo rss,comm --sort=-rss 2>/dev/null | head -15 || ps aux --sort=-rss | head -15' +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_probe_neko_mem.sh", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command("bash /tmp/_probe_neko_mem.sh", timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_new_vps_108.py b/scripts/_probe_new_vps_108.py new file mode 100644 index 0000000..f6049df --- /dev/null +++ b/scripts/_probe_new_vps_108.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Probe 108.174.50.68 for old douyinWEB / dy.nomadro.live install.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +USER = "root" +PASS = "Xiao4669805" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + USER, + PASS, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=60): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return code, out + + +c = ssh() +run( + c, + r""" +set +e +echo ===HOST=== +uname -a +free -h +df -h / +echo ===OLD_PATHS=== +ls -la /opt/douyinWEB 2>/dev/null | head -20 +ls -la /var/www 2>/dev/null | head +ls -la /etc/douyinweb.env /etc/systemd/system/douyinweb* 2>/dev/null +echo ===UNITS=== +systemctl list-units --all 'douyinweb*' --no-pager 2>/dev/null +systemctl list-unit-files 'douyinweb*' --no-pager 2>/dev/null +echo ===DOCKER=== +docker ps -a --format '{{.Names}} {{.Status}}' 2>/dev/null | head -40 +echo ===CADDY_NGINX=== +ls /etc/caddy 2>/dev/null; ls /etc/nginx/sites-enabled 2>/dev/null +grep -RIn 'nomadro\|douyinWEB\|8014\|4015' /etc/caddy /etc/nginx 2>/dev/null | head -40 +echo ===PORTS=== +ss -lntp | grep -E ':80|:443|:8014|:4015|:8080|:3000|:5173' || true +echo ===DISK_APP=== +du -sh /opt/douyinWEB /opt/* 2>/dev/null | head -30 +""", +) +c.close() diff --git a/scripts/_probe_oauth_anomaly.py b/scripts/_probe_oauth_anomaly.py new file mode 100644 index 0000000..f6fc787 --- /dev/null +++ b/scripts/_probe_oauth_anomaly.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +"""Read-only: why assign cards show OAuth异常 on dylive.""" +import json +import paramiko + +REMOTE = r'''#!/bin/bash +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +curl -sS -m 60 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups > /tmp/groups.json +python3 - <<'PY' +import json +rows=json.load(open("/tmp/groups.json")) +groups=rows if isinstance(rows,list) else rows.get("groups") or [] +print("group_count", len(groups)) +keys=("name","oauth_ok","oauth_status","oauth_error","oauth_message","token_ok","has_refresh_token", + "channel_pk","youtube_oauth","oauth","client","profile","auth_error","token_error") +# print first group keys related to oauth +if groups: + g0=groups[0] + oauth_keys=sorted(k for k in g0.keys() if "oauth" in k.lower() or "token" in k.lower() or "auth" in k.lower() or "ypp" in k.lower()) + print("oauth_related_keys", oauth_keys) +for g in groups: + name=str(g.get("name") or "") + interesting=any(x in name.lower() for x in ("nomadvlog","nice street","china street","nomadesim","asian","nomadro")) + # also dump any with oauth fail flags + flags=[] + for k,v in g.items(): + lk=k.lower() + if "oauth" in lk or "token" in lk: + if v not in (None,"",0,False,[],{}): + flags.append(f"{k}={v!r}"[:120]) + if interesting or any("异常" in str(v) or v is False for k,v in g.items() if "oauth" in k.lower()): + print("---", name) + print(" id", g.get("id")) + print(" channel_pk", g.get("channel_pk"), "yt", g.get("youtube_channel_id")) + print(" enabled", g.get("enabled"), "category", g.get("category")) + for line in flags[:20]: + print(" ", line) +PY +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_probe_oauth.sh", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command("bash /tmp/_probe_oauth.sh", timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_oauth_cause.py b/scripts/_probe_oauth_cause.py new file mode 100644 index 0000000..c60fa65 --- /dev/null +++ b/scripts/_probe_oauth_cause.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r'''#!/bin/bash +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +chs = db.list_shorts_channels() +print("=== shorts channels by profile ===") +for c in sorted(chs, key=lambda x: (str(x.get("oauth_profile_id") or ""), str(x.get("name") or ""))): + if not c.get("enabled"): + continue + err=(c.get("oauth_error") or "").replace("\n"," ")[:90] + print(f"profile={c.get('oauth_profile_id') or '-'} | oauth_ok={c.get('oauth_ok')} | {c.get('name')} | err={err!r}") + +# recent settings related to shorts / quota +cfg=db.get_settings_map() +for k in sorted(cfg): + if "shorts" in k.lower() and ("quota" in k.lower() or "cooldown" in k.lower() or "enabled" in k.lower()): + print("setting", k, "=", cfg.get(k)) +PY + +echo '=== recent api log oauth/refresh/revoked ===' +journalctl -u douyinweb-api --since "24 hours ago" --no-pager 2>/dev/null | grep -iE 'revoked|invalid_grant|OAuth 刷新|refresh.*fail|quota' | tail -40 +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_probe_oauth_cause.sh", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command("bash /tmp/_probe_oauth_cause.sh", timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_oauth_lives_now.py b/scripts/_probe_oauth_lives_now.py new file mode 100644 index 0000000..4140fd0 --- /dev/null +++ b/scripts/_probe_oauth_lives_now.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +"""OAuth + live-map via API venv and session cookie.""" +from __future__ import annotations + +import json +import paramiko + +REMOTE = r''' +import json, os, sys, asyncio, urllib.request, http.cookiejar +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") + +# mimic API env +os.environ.setdefault("DY_YOUTUBE_SVC_URL", "http://127.0.0.1:8020") + +async def main(): + from app import db, youtube_live + from app import youtube_manage + + groups = [g for g in db.list_yt_assign_groups() if g.get("enabled")] + print("=== oauth liveBroadcasts ===") + for g in groups: + pk = str(g.get("channel_pk") or "").strip() + cid = str(g.get("youtube_channel_id") or "").strip() + name = g.get("name") + if not pk: + print(name, "no pk"); continue + ch = db.get_shorts_channel(pk) or {} + if not str(ch.get("refresh_token") or "").strip(): + print(name, "no refresh_token"); continue + try: + token, _ = await youtube_manage._access_for_channel(pk) + data = await youtube_manage._get( + "liveBroadcasts", + token=token, + params={"part":"id,snippet,status","mine":"true","maxResults":25}, + ) + items = data.get("items") or [] + lives=[] + for it in items: + st=str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower() + sn=it.get("snippet") or {} + lives.append((st, it.get("id"), (sn.get("title") or "")[:50])) + live_only=[x for x in lives if x[0]=="live"] + print(name, (cid or "-")[:14], "n", len(items), "live", live_only, "all_status", sorted(set(x[0] for x in lives))) + except Exception as e: + print(name, "OAUTH_ERR", type(e).__name__, str(e)[:200]) + + print("=== build_live_map force ===") + youtube_live._CACHE["at"]=0 + youtube_live._CACHE["payload"]=None + p = await youtube_live.build_live_map(force=True) + print("live_count", p.get("live_count"), "source", p.get("source"), "svc_error", (p.get("svc_error") or "")[:120]) + for k,v in sorted((p.get("entries") or {}).items()): + if k.startswith("assign:"): + print((" LIVE" if v.get("is_live") else " off "), k, v.get("source"), (v.get("title") or "")[:36], (v.get("live_url") or "")[:70], "err", (v.get("error") or "")[:80]) + +asyncio.run(main()) +''' + + +def run(port, user, pwd, label, py="/opt/douyinWEB/backend/.venv/bin/python"): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + # also curl live-map with login + login = r''' +python3 - <<'PY' +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +# try login +for path in ["/api/auth/login","/api/session/login","/api/login"]: + try: + req=urllib.request.Request("http://127.0.0.1:8014"+path, data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") + r=op.open(req, timeout=15) + print("login", path, r.status, r.read()[:80]) + break + except Exception as e: + print("login fail", path, e) +try: + raw=op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=120).read() + p=json.loads(raw) + print("api live_count", p.get("live_count"), "source", p.get("source"), "svc", (p.get("svc_error") or "")[:100]) + for k,v in (p.get("entries") or {}).items(): + if v.get("is_live"): + print(" LIVE", k, v.get("source"), (v.get("title") or "")[:40], (v.get("live_url") or "")[:80]) +except Exception as e: + print("api map ERR", e) +PY +''' + stdin, stdout, stderr = c.exec_command( + f"cd /opt/douyinWEB/backend && {py} - <<'PY'\n" + REMOTE + "\nPY\n" + login, + timeout=300, + ) + # Wait - heredoc nesting is messy. Use stdin pipe instead. + c.close() + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command(f"cd /opt/douyinWEB/backend && {py} -", timeout=300) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "venv ########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-2500:]) + c.close() + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=180) + stdin.write( + """ +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +for path in ["/api/auth/login","/api/session/login","/api/login"]: + try: + req=urllib.request.Request("http://127.0.0.1:8014"+path, data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") + r=op.open(req, timeout=15) + print("login", path, r.status, r.read()[:120]) + break + except Exception as e: + print("login fail", path, type(e).__name__, e) +try: + raw=op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=120).read() + p=json.loads(raw) + print("api live_count", p.get("live_count"), "source", p.get("source"), "svc", (p.get("svc_error") or "")[:120]) + for k,v in (p.get("entries") or {}).items(): + if v.get("is_live"): + print(" LIVE", k, v.get("source"), (v.get("title") or "")[:40], (v.get("live_url") or "")[:80]) +except Exception as e: + print("api map ERR", type(e).__name__, e) +""" + ) + stdin.channel.shutdown_write() + print("########", label, "api ########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-800:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys") diff --git a/scripts/_probe_oauth_shorts.py b/scripts/_probe_oauth_shorts.py new file mode 100644 index 0000000..f83eb4f --- /dev/null +++ b/scripts/_probe_oauth_shorts.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r'''#!/bin/bash +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +from app import yt_assign_db +groups = yt_assign_db.list_groups(include_urls=False) +print("=== shorts oauth for assign channel_pks ===") +for g in groups: + pk = str(g.get("channel_pk") or "") + name = g.get("name") + ch = db.get_shorts_channel(pk) if pk else None + if not ch: + print(f"MISSING_CH | {name} | pk={pk}") + continue + err = (ch.get("oauth_error") or "").replace("\n"," ")[:120] + print( + f"{name} | oauth_ok={ch.get('oauth_ok')} | profile={ch.get('oauth_profile_id')} | " + f"rt={bool(ch.get('refresh_token'))} | err={err!r} | checked={ch.get('oauth_checked_at')}" + ) + +chs = db.list_shorts_channels() +bad=[c for c in chs if int(c.get('oauth_ok') if c.get('oauth_ok') is not None else -1)==0] +print("bad_count", len(bad), "/", len(chs)) +for c in bad: + err=(c.get("oauth_error") or "").replace("\n"," ")[:140] + print(" BAD", c.get("name"), "|", err, "| profile", c.get("oauth_profile_id")) +PY +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_probe_oauth2.sh", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command("bash /tmp/_probe_oauth2.sh", timeout=60) +out = (o.read() + e.read()).decode("utf-8", "replace") +open(r"c:\Users\admin\Desktop\douyinWEB\scripts\_oauth_probe_out.txt", "w", encoding="utf-8").write(out) +print(out) +c.close() diff --git a/scripts/_probe_oauth_yt_svc.py b/scripts/_probe_oauth_yt_svc.py new file mode 100644 index 0000000..766a66e --- /dev/null +++ b/scripts/_probe_oauth_yt_svc.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +"""OAuth broadcasts via venv; youtube-svc /batch/live; asian studio snapshot.""" +from __future__ import annotations + +import sys + +import paramiko + +REMOTE = r''' +import json, os, sys, asyncio, urllib.request, sqlite3 +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +os.environ.setdefault("DY_YOUTUBE_SVC_URL", "http://127.0.0.1:8020") + +# youtube-svc +print("=== youtube-svc batch/live ===") +body=json.dumps({"items":[ + "https://www.youtube.com/channel/UCXFErW9DeE8EXrInlnyCnVw", + "https://www.youtube.com/channel/UCjQ8jnBm2N4FGRowNXcXThw", + "https://www.youtube.com/channel/UCYnwXkCMmVFf8Vr6MlWb-Jw", + "https://www.youtube.com/channel/UCf-uYs6f5yg3iWylnHkIKug", +]}).encode() +for path in ["/batch/live","/api/batch/live","/live/batch"]: + try: + req=urllib.request.Request("http://127.0.0.1:8020"+path, data=body, headers={"Content-Type":"application/json"}, method="POST") + raw=urllib.request.urlopen(req, timeout=120).read().decode() + print(path, raw[:2000]) + break + except Exception as e: + print(path, "ERR", e) + +async def main(): + from app import db, youtube_manage + # discover API + names=[n for n in dir(db) if "assign" in n.lower()] + print("db assign fns", names) + groups=[] + if hasattr(db, "list_yt_assign_groups"): + groups=db.list_yt_assign_groups() + elif hasattr(db, "yt_assign_list_groups"): + groups=db.yt_assign_list_groups() + else: + con=sqlite3.connect("data/monitor.db"); con.row_factory=sqlite3.Row + groups=[dict(r) for r in con.execute("select * from yt_assign_groups where enabled=1")] + print("=== oauth ===") + for g in groups: + if not g.get("enabled") and "enabled" in g and not g["enabled"]: + continue + if g.get("enabled") in (0, False, "0"): + continue + pk=str(g.get("channel_pk") or "").strip() + cid=str(g.get("youtube_channel_id") or "").strip() + name=g.get("name") + if not pk: + print(name,"no pk"); continue + try: + ch=db.get_shorts_channel(pk) or {} + except Exception: + con=sqlite3.connect("data/monitor.db"); con.row_factory=sqlite3.Row + r=con.execute("select * from shorts_channels where id=?", (pk,)).fetchone() + ch=dict(r) if r else {} + if not str(ch.get("refresh_token") or "").strip(): + print(name,"no token"); continue + try: + token,_=await youtube_manage._access_for_channel(pk) + data=await youtube_manage._get("liveBroadcasts", token=token, params={"part":"id,snippet,status","mine":"true","maxResults":25}) + items=data.get("items") or [] + rows=[] + for it in items: + st=str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower() + sn=it.get("snippet") or {} + rows.append((st, it.get("id"), (sn.get("title") or "")[:45])) + print(name, cid[:14], "live", [r for r in rows if r[0]=="live"], "status_set", sorted(set(r[0] for r in rows)), "n", len(rows)) + except Exception as e: + print(name,"ERR", type(e).__name__, str(e)[:220]) + + # studio telemetry latest + print("=== studio telemetry files ===") + import glob + for p in sorted(glob.glob("/opt/douyinWEB/backend/data/neko/studio_telemetry*.json"))[:5]: + try: + obj=json.load(open(p,encoding="utf-8")) + print(p, json.dumps(obj, ensure_ascii=False)[:500]) + except Exception as e: + print(p, e) + +asyncio.run(main()) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + py = "/opt/douyinWEB/backend/.venv/bin/python" + stdin, stdout, stderr = c.exec_command(f"cd /opt/douyinWEB/backend && {py} -", timeout=300) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + out = stdout.read().decode("utf-8", "replace") + err = stderr.read().decode("utf-8", "replace") + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + print(out) + if err.strip(): + print("STDERR", err[-2000:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys") diff --git a/scripts/_probe_ops1_dom_now.py b/scripts/_probe_ops1_dom_now.py new file mode 100644 index 0000000..0a5b66d --- /dev/null +++ b/scripts/_probe_ops1_dom_now.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Physical ops-neko-1: page URL + DOM nodata/on_air.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + # upload scrape + with sftp.file("/tmp/cdp_studio_scrape.py", "wb") as f: + f.write(open(r"c:\Users\admin\Desktop\douyinWEB\backend\neko\cdp_studio_scrape.py", "rb").read()) + sftp.close() + cmd = ( + "echo '4669805' | sudo -S -p '' bash -lc " + "'docker exec -i douyinweb-ops-neko-1 python3 - < /tmp/cdp_studio_scrape.py; " + "curl -sS -m 5 -o /dev/null -w cn_ops1=%{http_code}\\\\n https://dy.nomadro.cn/ops-neko/1/'" + ) + _i, o, e = c.exec_command(cmd, timeout=45) + print((o.read() + e.read()).decode("utf-8", "replace")[:3000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_ops2_dom.py b/scripts/_probe_ops2_dom.py new file mode 100644 index 0000000..812da18 --- /dev/null +++ b/scripts/_probe_ops2_dom.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""CDP-read ops-neko-2 Studio DOM (nodata / 待开播) — read only.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +N=douyinweb-ops-neko-2 +docker exec -i "$N" python3 - <<'PY' +import json, re, urllib.request +tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read()) +live=[t for t in tabs if 'livestreaming' in (t.get('url') or '').lower()] +print('live_tabs', len(live)) +for t in live[:3]: + print('URL', (t.get('url') or '')[:120]) +# use existing scrape script if present +import subprocess, os +for p in ['/etc/neko/cdp_studio_scrape.py','/opt/neko/cdp_studio_scrape.py']: + if os.path.isfile(p): + print('scrape', p) + print(subprocess.check_output(['python3',p], text=True, timeout=20)[:2000]) + break +else: + # inline minimal + import base64, socket, struct, time, os as _os + if not live: + print('no live'); raise SystemExit + ws=live[0].get('webSocketDebuggerUrl') or '' + # fallback: just print titles + print('ws', bool(ws)) +PY +# also copy scrape from host if mounted +ls /opt/douyinWEB/backend/neko/cdp_studio_scrape.py 2>/dev/null +docker exec "$N" bash -lc 'test -f /etc/neko/cdp_studio_scrape.py && python3 /etc/neko/cdp_studio_scrape.py || true' 2>/dev/null | head -c 2500 +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_ops2_dom.sh", "w") as f: + f.write(SCRIPT) + # also upload scrape via stdin to docker + scrape = open( + r"c:\Users\admin\Desktop\douyinWEB\backend\neko\cdp_studio_scrape.py", + "rb", + ).read() + with sftp.file("/tmp/cdp_studio_scrape.py", "wb") as f: + f.write(scrape) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc " + "'docker exec -i douyinweb-ops-neko-2 python3 - < /tmp/cdp_studio_scrape.py'", + timeout=60, + ) + print((o.read() + e.read()).decode("utf-8", "replace")[:4000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_opsneko_bl_mount.py b/scripts/_probe_opsneko_bl_mount.py new file mode 100644 index 0000000..a6c05a5 --- /dev/null +++ b/scripts/_probe_opsneko_bl_mount.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SH = r""" +set -e +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + docker inspect "$name" --format '{{range .Mounts}}{{.Source}} -> {{.Destination}} ({{.Mode}}){{println}}{{end}}' | grep -E 'neko|browser|policy|tamper|opt/douyin' || true + echo --- browser-launch head --- + docker exec "$name" head -n 5 /etc/neko/browser-launch.sh + echo --- has tm load? --- + docker exec "$name" grep -n "Offline Tampermonkey\|tm_load_dir\|load-extension" /etc/neko/browser-launch.sh | head -20 || true + echo --- host opt browser-launch has tm? --- + grep -n "Offline Tampermonkey\|tm_load_dir" /opt/douyinWEB/backend/neko/browser-launch.sh | head -10 || true +done +# find image/compose source for browser-launch +ls -la /opt/douyinWEB/backend/neko/browser-launch.sh +# check if compose mounts it +ls /opt/douyinWEB/docker* 2>/dev/null; ls /opt/douyinWEB/*compose* 2>/dev/null; ls /opt/douyinWEB/backend/neko/*compose* 2>/dev/null +find /opt/douyinWEB -name '*ops*neko*' -o -name '*compose*.yml' 2>/dev/null | head -40 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_tm_find_mount.sh", "wb") as f: + f.write(SH.encode()) + sftp.close() + _i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_tm_find_mount.sh", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_opsneko_tm_load.py b/scripts/_probe_opsneko_tm_load.py new file mode 100644 index 0000000..07c3fe3 --- /dev/null +++ b/scripts/_probe_opsneko_tm_load.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Check Chrome version, locales, TM service worker, store reachability on ops-neko.""" +import base64 +import json +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PROBE = r''' +import json, urllib.request, subprocess, os +from pathlib import Path + +print("chrome_ver", subprocess.getoutput("google-chrome --version || google-chrome-stable --version")) +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +root=Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0") +print("locales", (root/"_locales").exists(), "count", len(list((root/"_locales").iterdir())) if (root/"_locales").exists() else 0) +print("en_messages", (root/"_locales/en/messages.json").exists()) +print("metadata", list((root/"_metadata").iterdir()) if (root/"_metadata").exists() else None) +# store reach +for url in [ + "https://clients2.google.com/service/update2/crx", + "https://clients2.googleusercontent.com/", +]: + try: + req=urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=8) as r: + print("reach", url, r.status) + except Exception as e: + print("reach_fail", url, type(e).__name__, str(e)[:120]) +# CDP service workers / extension pages +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +except Exception as e: + print("cdp_fail", e); raise SystemExit +print("tabs", len(tabs)) +for t in tabs: + u=t.get("url") or "" + typ=t.get("type") + if typ=="service_worker" or "dhdgff" in u or "chrome://extensions" in u or "chrome-extension://" in u: + print("HIT", typ, (t.get("title") or "")[:50], u[:160]) +# open extensions page if missing +has_ext_page=any("chrome://extensions" in (t.get("url") or "") for t in tabs) +if not has_ext_page: + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/new?chrome://extensions/", timeout=5) + print("opened_extensions_page") + except Exception as e: + print("open_ext_fail", e) +''' + +B64 = base64.b64encode(PROBE.encode()).decode() + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + remote = f""" +echo 4669805 | sudo -S -p '' bash -lc ' +B64="{B64}" +for i in 1 2; do + echo "===== OPS$i =====" + printf %s "$B64" | docker exec -i douyinweb-ops-neko-$i bash -lc "base64 -d > /tmp/_tm_probe.py && python3 /tmp/_tm_probe.py" +done +' +""" + _i, o, e = c.exec_command(remote, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_opsneko_tm_load2.py b/scripts/_probe_opsneko_tm_load2.py new file mode 100644 index 0000000..5cafe79 --- /dev/null +++ b/scripts/_probe_opsneko_tm_load2.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe Tampermonkey load status inside ops-neko containers.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PROBE = r''' +import json, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +p=Path("/home/neko/.config/google-chrome/Default/Preferences") +d=json.loads(p.read_text()) +e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state")) +print("location", e.get("location")) +print("from_webstore", e.get("from_webstore")) +print("path", e.get("path")) +print("disable_reasons", e.get("disable_reasons")) +print("was_installed_by_oem", e.get("was_installed_by_oem")) +pol_path=Path("/etc/opt/chrome/policies/managed/policies.json") +pol=json.loads(pol_path.read_text()) +print("forcelist", pol.get("ExtensionInstallForcelist")) +print("jsonImport", ((pol.get("3rdparty") or {}).get("extensions") or {}).get(ext)) +# CDP tabs +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +except Exception as ex: + print("cdp_err", ex) + tabs=[] +print("tabs_total", len(tabs)) +for t in tabs: + u=t.get("url") or "" + if "dhdgff" in u or t.get("type")=="service_worker": + print("TAB", t.get("type"), t.get("title"), u[:120]) +# check extension dir +ext_root=Path("/home/neko/.config/google-chrome/Default/Extensions")/ext +print("ext_exists", ext_root.exists()) +if ext_root.exists(): + vers=sorted([x.name for x in ext_root.iterdir() if x.is_dir()]) + print("versions", vers) + if vers: + mf=ext_root/vers[0]/"manifest.json" + if mf.exists(): + m=json.loads(mf.read_text()) + print("manifest_name", m.get("name"), "version", m.get("version"), "mv", m.get("manifest_version")) +# LES +les=Path("/home/neko/.config/google-chrome/Default/Local Extension Settings")/ext +print("les_exists", les.exists()) +if les.exists(): + print("les_files", sorted([x.name for x in les.iterdir()])[:20]) +''' + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + for i in (1, 2): + name = f"douyinweb-ops-neko-{i}" + print(f"===== {name} =====") + cmd = f"docker exec {name} python3 -c {json_quote(PROBE)}" + # write probe via stdin + _i, o, e = c.exec_command( + f"echo 4669805 | sudo -S -p '' docker exec -i {name} python3 -", + timeout=60, + ) + _i.write(PROBE.encode()) + _i.channel.shutdown_write() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out) + c.close() + + +def json_quote(_s: str) -> str: + return "" + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_phys_guest_identity.py b/scripts/_probe_phys_guest_identity.py new file mode 100644 index 0000000..62f6ed0 --- /dev/null +++ b/scripts/_probe_phys_guest_identity.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Identify which guest we hit via FRP:4014 vs PVE VM 103.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = """#!/bin/bash +echo '=== identity ===' +hostname -f 2>/dev/null || hostname +cat /etc/hostname 2>/dev/null +echo '=== MAC / IP ===' +ip -br link +ip -br addr +echo '=== mem / balloon ===' +free -h +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo +# virtio balloon often shows under /sys +ls /sys/bus/virtio/devices 2>/dev/null +find /sys -name '*balloon*' 2>/dev/null | head -20 +cat /sys/devices/system/memory/block_size_bytes 2>/dev/null +echo memory_blocks=$(ls -d /sys/devices/system/memory/memory* 2>/dev/null | wc -l) +echo '=== dmidecode mem (if any) ===' +dmidecode -t 17 2>/dev/null | grep -E 'Size:|Locator:' | head -20 || true +echo '=== qemu guest agent? ===' +systemctl is-active qemu-guest-agent 2>/dev/null || true +which qemu-ga 2>/dev/null || true +echo '=== neko present? ===' +docker ps --format '{{.Names}}' 2>/dev/null | grep -E 'neko|douyin' | head -20 +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_id_guest.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_id_guest.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_probe_phys_mem_neko3.py b/scripts/_probe_phys_mem_neko3.py new file mode 100644 index 0000000..e63a908 --- /dev/null +++ b/scripts/_probe_phys_mem_neko3.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Read-only: physical host memory + neko3 crash clues.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r""" +set -e +echo '=== MEM free -h ===' +free -h +echo '=== MEMINFO ===' +grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit' /proc/meminfo +echo '=== API host metrics ===' +curl -sS -m 8 http://127.0.0.1:8014/api/host/metrics 2>/dev/null | head -c 500; echo +echo '=== NEKO containers ===' +docker ps -a --filter name=neko --format 'table {{.Names}}\t{{.Status}}\t{{.RunningFor}}' 2>/dev/null | head -40 +echo '=== docker stats ===' +docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.CPUPerc}}' 2>/dev/null | head -40 +echo '=== neko3 inspect ===' +docker inspect douyinweb-neko-3 --format 'Status={{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Restart={{.RestartCount}} Started={{.State.StartedAt}} Finished={{.State.FinishedAt}} Error={{.State.Error}}' 2>/dev/null || echo 'no douyinweb-neko-3' +docker inspect neko-3 --format 'Status={{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Restart={{.RestartCount}}' 2>/dev/null || true +echo '=== OOM dmesg/journal ===' +dmesg -T 2>/dev/null | grep -iE 'oom|Out of memory|Killed process|chrome' | tail -40 || true +journalctl -k --since '3 days ago' 2>/dev/null | grep -iE 'oom|Killed process' | tail -30 || true +echo '=== chrome inside neko3 ===' +CID=$(docker ps -q --filter name=douyinweb-neko-3 | head -1) +if [ -z "$CID" ]; then CID=$(docker ps -aq --filter name=neko-3 | head -1); fi +echo CID=$CID +if [ -n "$CID" ]; then + docker exec "$CID" bash -lc 'ps aux --sort=-%mem | head -25' 2>/dev/null || true + docker logs --tail 80 "$CID" 2>&1 | tail -80 || true +fi +echo '=== PVE balloon hint (guest sees) ===' +cat /sys/devices/system/memory/*/online 2>/dev/null | wc -l || true +lscpu | grep -E 'CPU\(s\)|Model name' || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + cmd = "echo '4669805' | sudo -S -p '' bash -s" + _, o, e = c.exec_command(cmd, timeout=120) + o.channel.sendall(SCRIPT.encode()) + o.channel.shutdown_write() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_probe_phys_mem_neko3b.py b/scripts/_probe_phys_mem_neko3b.py new file mode 100644 index 0000000..82ae823 --- /dev/null +++ b/scripts/_probe_phys_mem_neko3b.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 90) -> str: + print(f"\n$ {cmd[:160]}", flush=True) + _, o, e = c.exec_command(cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-8000:] if len(out) > 8000 else out, flush=True) + return out + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sp = "echo '4669805' | sudo -S -p '' " + run(c, sp + "free -h") + run(c, sp + "grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit' /proc/meminfo") + run(c, "curl -sS -m 8 http://127.0.0.1:8014/api/ops/host-metrics || curl -sS -m 8 http://127.0.0.1:8014/api/host/metrics || true") + run(c, sp + "docker ps -a --filter name=neko --format 'table {{.Names}}\\t{{.Status}}\\t{{.RunningFor}}'") + run(c, sp + "docker stats --no-stream --format 'table {{.Name}}\\t{{.MemUsage}}\\t{{.MemPerc}}\\t{{.CPUPerc}}'") + run( + c, + sp + + "docker inspect douyinweb-neko-3 --format 'Status={{.State.Status}} OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Restart={{.RestartCount}} Started={{.State.StartedAt}} Error={{.State.Error}}' 2>/dev/null || echo missing-neko-3", + ) + run(c, sp + "dmesg -T 2>/dev/null | grep -iE 'oom|Out of memory|Killed process' | tail -40 || true") + run(c, sp + "journalctl -k --since '3 days ago' 2>/dev/null | grep -iE 'oom|Killed process' | tail -30 || true") + run( + c, + sp + + "bash -lc 'CID=$(docker ps -q --filter name=douyinweb-neko-3 | head -1); echo CID=$CID; " + "if [ -n \"$CID\" ]; then docker exec $CID ps aux --sort=-%mem 2>/dev/null | head -20; " + "docker logs --tail 60 $CID 2>&1 | tail -60; fi'", + ) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_probe_preparing_flap.py b/scripts/_probe_preparing_flap.py new file mode 100644 index 0000000..972372c --- /dev/null +++ b/scripts/_probe_preparing_flap.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +import sys, json, paramiko +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245",22,"root","Xiao4669805",timeout=30,allow_agent=False,look_for_keys=False) +cmd=r''' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import yt_assign_db, youtube_relay_db, db +from app.youtube_relay_pipeline import youtube_relay_pipeline +import json +g=[x for x in yt_assign_db.list_groups(include_urls=False) if "asian" in str(x.get("name") or "").lower() and x.get("category")=="time_slot"] +print("groups", [(x.get("name"), x.get("id"), x.get("neko_instance_id")) for x in g]) +for x in g: + st=youtube_relay_db.get_relay_state(x["id"]) or {} + print("relay_state", {k:st.get(k) for k in ("status","source_url","source_room_id","error","ffmpeg_pid","updated_at")}) + print("recent", (st.get("recent_log") or "")[-400:] if isinstance(st.get("recent_log"),str) else (st.get("recent_log") or [])[-8:]) +cfg=db.get_settings_map() +print("settings", {k:cfg.get(k) for k in ("youtube_relay_enabled","youtube_relay_timeslot_test","youtube_relay_timeslot_test_group_id","youtube_relay_exclusive_live")}) +st=youtube_relay_pipeline.status() +for e in (st.get("entries") or st.get("groups") or [])[:20]: + name=e.get("name") or e.get("group_name") or "" + if "asian" in str(name).lower() or e.get("group_id") in {x.get("id") for x in g}: + print("status_entry", {k:e.get(k) for k in ("group_id","name","status","business_status","is_pushing","source_url","error","monitor_label","label") if k in e or True}) + print("keys", sorted(e.keys())[:40]) +PY +echo '=== neko7 scrape ===' +docker ps --filter name=douyinweb-neko-7 --format '{{.Names}} {{.Status}}' +docker exec -i douyinweb-neko-7 python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py 2>/dev/null | tail -1 | python3 -c 'import sys,json;d=json.load(sys.stdin);print({k:d.get(k) for k in ("live_status","on_air","health","url")}); t=(d.get("text") or "")[:800]; print("preparing", "preparing" in t.lower()); print("snippet", t[:500])' +echo '=== ffmpeg ===' +ps -eo pid,etime,args | grep -i '[f]fmpeg.*youtube' | head -3 +''' +_,o,e=c.exec_command(cmd,timeout=60) +print((o.read()+e.read()).decode()) +c.close() diff --git a/scripts/_probe_public_mux.py b/scripts/_probe_public_mux.py new file mode 100644 index 0000000..bac4ef2 --- /dev/null +++ b/scripts/_probe_public_mux.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_i, o, e = c.exec_command( + "nc -vz -w 3 82.157.112.245 62300 2>&1; nc -vz -w 3 82.157.112.245 52300 2>&1", + timeout=20, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_real_yt_lives.py b/scripts/_probe_real_yt_lives.py new file mode 100644 index 0000000..c25c861 --- /dev/null +++ b/scripts/_probe_real_yt_lives.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Probe which assign channels are actually live vs youtubei.""" +from __future__ import annotations + +import json +import sys +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CARDS = [ + ("asian streetfood", "UCXFErW9DeE8EXrInlnyCnVw"), + ("hackrobotlite", "UCYnwXkCMmVFf8Vr6MlWb-Jw"), + ("nomad Street Food", "UCf-uYs6f5yg3iWylnHkIKug"), + ("Nomadro Hub", "UC-8V3pDMlM2B75fvbYRBsNg"), + ("walking tour", "UC0ojQ8aKSSOse1z-FGcUKUw"), + ("nomad vlog", "UCtVfMFdLTN4ap__8g7MFtVw"), + ("asian streetfood2", "UCjQ8jnBm2N4FGRowNXcXThw"), + ("nomadvlog", "UCO9wMc9tj9mD221Gu0rLBeA"), +] + + +def http_get(url: str, timeout: float = 12.0) -> tuple[int, str]: + req = urllib.request.Request( + url, + headers={ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Accept-Language": "en-US,en;q=0.9", + }, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace") + except Exception as ex: + return 0, f"{type(ex).__name__}: {ex}" + + +def page_looks_live(html: str) -> dict: + low = html.lower() + hits = { + "isLiveNow": '"islivenow":true' in low or '"isLiveNow":true' in html, + "LIVE_badge": "\"style\":\"LIVE\"" in html or ">LIVE<" in html, + "watching_now": "watching now" in low or "watching" in low and "viewers" in low, + "live_stream": "live stream" in low or "livestream" in low, + "hqdefault_live": "hqdefault_live" in low, + } + # videoId from canonical /watch + vid = "" + import re + + m = re.search(r"https://www\.youtube\.com/watch\?v=([a-zA-Z0-9_-]{6,})", html) + if m: + vid = m.group(1) + if not vid: + m = re.search(r'"videoId":"([a-zA-Z0-9_-]{11})".{0,80}"isLiveNow":true', html) + if m: + vid = m.group(1) + hits["video_id"] = vid + hits["likely_live"] = bool(hits["isLiveNow"] or hits["hqdefault_live"] or (hits["LIVE_badge"] and vid)) + return hits + + +def main(): + print("=== public channel pages (from this machine) ===") + for name, cid in CARDS: + url = f"https://www.youtube.com/channel/{cid}/live" + code, body = http_get(url) + if code != 200: + # fallback channel home + code2, body2 = http_get(f"https://www.youtube.com/channel/{cid}") + print(f"{name} {cid} /live->{code} home->{code2}") + body = body2 if code2 == 200 else body + else: + print(f"{name} {cid} /live->{code}") + info = page_looks_live(body if isinstance(body, str) else "") + print(" ", info) + + # VPS youtubei all 8 + print("\n=== VPS youtubei batch ===") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + script = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0,".") +from app import youtube_client +URLS=[ +"https://www.youtube.com/channel/UCXFErW9DeE8EXrInlnyCnVw", +"https://www.youtube.com/channel/UCYnwXkCMmVFf8Vr6MlWb-Jw", +"https://www.youtube.com/channel/UCf-uYs6f5yg3iWylnHkIKug", +"https://www.youtube.com/channel/UC-8V3pDMlM2B75fvbYRBsNg", +"https://www.youtube.com/channel/UC0ojQ8aKSSOse1z-FGcUKUw", +"https://www.youtube.com/channel/UCtVfMFdLTN4ap__8g7MFtVw", +"https://www.youtube.com/channel/UCjQ8jnBm2N4FGRowNXcXThw", +"https://www.youtube.com/channel/UCO9wMc9tj9mD221Gu0rLBeA", +] +async def main(): + # also try /live URLs + live_urls=[u+"/live" for u in URLS] + for label, items in [("channel", URLS), ("channel/live", live_urls)]: + data=await youtube_client.batch_live(items) + n=0 + print("BATCH", label) + for r in data.get("results") or []: + if r.get("is_live"): + n+=1 + live=r.get("live") or {} + print(" LIVE", r.get("channel_id"), live.get("title"), live.get("url")) + else: + print(" off ", r.get("channel_id"), "err", (r.get("error") or "")[:50]) + print(" live_n", n) +asyncio.run(main()) +''' + sftp = c.open_sftp() + with sftp.file("/tmp/_probe_all_live.py", "w") as f: + f.write(script) + sftp.close() + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python /tmp/_probe_all_live.py", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_studio_video_ids.py b/scripts/_probe_studio_video_ids.py new file mode 100644 index 0000000..ab4f014 --- /dev/null +++ b/scripts/_probe_studio_video_ids.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +"""Truth: player API for Studio video IDs + channel /live via youtubei player.""" +from __future__ import annotations + +import json +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, re, urllib.request, socket + +proxy="" +s=socket.socket(); s.settimeout(0.4) +try: + s.connect(("127.0.0.1",7890)); proxy="http://127.0.0.1:7890" +except Exception: + proxy="" +finally: + s.close() + +def opener(px): + handlers=[] + if px: + handlers.append(urllib.request.ProxyHandler({"http":px,"https":px})) + return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + +def player(vid): + body=json.dumps({ + "context":{"client":{"clientName":"WEB","clientVersion":"2.20250301.00.00","hl":"en","gl":"US"}}, + "videoId":vid + }).encode() + req=urllib.request.Request( + "https://www.youtube.com/youtubei/v1/player?prettyPrint=false", + data=body, + headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0","X-YouTube-Client-Name":"1","X-YouTube-Client-Version":"2.20250301.00.00"}, + method="POST", + ) + raw=opener(proxy).open(req, timeout=25).read().decode("utf-8","ignore") + obj=json.loads(raw) + vd=obj.get("videoDetails") or {} + mf=((obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}) + play=obj.get("playabilityStatus") or {} + return { + "title": (vd.get("title") or "")[:60], + "channel": (vd.get("author") or "")[:40], + "channelId": vd.get("channelId"), + "isLive": vd.get("isLive"), + "isLiveContent": vd.get("isLiveContent"), + "liveBroadcastDetails": mf.get("liveBroadcastDetails"), + "status": play.get("status"), + "reason": (play.get("reason") or "")[:80], + } + +vids=[ + "zblaCyR1AY8","XW-3kA3XdfI","aG0zIkmCJ2E","1cQY6jHytxQ","L1sF_kZvzIk", +] +print("proxy", proxy or "direct") +for vid in vids: + try: + print(vid, json.dumps(player(vid), ensure_ascii=False)) + except Exception as e: + print(vid, "ERR", e) + +# also scrape watch?v= pages for isLiveNow +print("--- watch html ---") +for vid in vids: + try: + req=urllib.request.Request("https://www.youtube.com/watch?v="+vid, headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-US"}) + html=opener(proxy).open(req, timeout=25).read().decode("utf-8","ignore") + now=bool(re.search(r'"isLiveNow"\s*:\s*true', html, re.I)) + live=bool(re.search(r'"isLive"\s*:\s*true', html, re.I)) + print(vid, "isLiveNow", now, "isLive", live, "len", len(html)) + except Exception as e: + print(vid, "ERR", e) + +# check if youtube.mjs has /live resolve +print("--- youtube.mjs snippet ---") +import os +p="/opt/douyinWEB/youtube-svc/src/youtube.mjs" +txt=open(p,encoding="utf-8",errors="ignore").read() +print("has /live resolve", "/live" in txt and "getBasicInfo" in txt) +# print function around live +idx=txt.find("channel/${") +print("file size", len(txt)) +for key in ["resolveChannelLive","/live","getBasicInfo","isLiveNow"]: + print(key, txt.count(key)) +''' + + +def run(port, user, pwd, label): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + stdin, stdout, stderr = c.exec_command("python3 -", timeout=180) + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-500:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") diff --git a/scripts/_probe_timeslot_test_ready.py b/scripts/_probe_timeslot_test_ready.py new file mode 100644 index 0000000..8bf4a02 --- /dev/null +++ b/scripts/_probe_timeslot_test_ready.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +"""Read-only check of two time_slot channels before auto-relay test.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def api(base: str): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + login = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + op.open( + urllib.request.Request( + base + "/api/auth/login", + data=login, + method="POST", + headers={"Content-Type": "application/json"}, + ), + timeout=30, + ) + + def get(path: str): + with op.open(urllib.request.Request(base + path), timeout=60) as r: + return json.loads(r.read().decode()) + + print(f"\n===== {base} =====") + groups = get("/api/youtube/assign/groups") + rows = groups.get("groups") or groups if isinstance(groups, list) else groups.get("groups") or [] + targets = [] + for g in rows: + name = str(g.get("name") or "") + if "asian streetfood" in name.lower() or name.lower() == "nomadro" or "nomadro" == name.lower(): + if str(g.get("category") or "") == "time_slot" or "asian" in name.lower() or name.lower() == "nomadro": + targets.append(g) + # also match by handle-ish + if not targets: + for g in rows: + n = str(g.get("name") or "").lower() + if "asian" in n or n == "nomadro": + targets.append(g) + + # de-dupe + seen = set() + uniq = [] + for g in targets: + gid = str(g.get("id") or "") + if gid in seen: + continue + seen.add(gid) + uniq.append(g) + + print("matched", len(uniq)) + for g in uniq: + print( + "-", + g.get("name"), + "id=", + g.get("id"), + "cat=", + g.get("category"), + "armed=", + g.get("time_slot_armed"), + "neko=", + g.get("neko_instance_id"), + "neko_en=", + g.get("neko_enabled"), + "prefer=", + g.get("neko_open_prefer"), + "key=", + bool(g.get("has_stream_key") or g.get("stream_key")), + "pool=", + len(g.get("pool") or []), + "feat=", + len(g.get("featured") or []), + "slots=", + len(g.get("slots") or []), + "oauth_profile=", + g.get("oauth_profile_id"), + ) + + try: + sch = get("/api/youtube/assign/schedule") + print( + "schedule mode=", + sch.get("time_slot_mode"), + "now=", + sch.get("now_label"), + "channels=", + sch.get("channel_count"), + ) + for ch in sch.get("channels") or []: + nm = str(ch.get("name") or "") + if "asian" in nm.lower() or nm.lower() == "nomadro": + print( + " slot", + nm, + "active=", + ch.get("active"), + ch.get("start_label"), + "-", + ch.get("end_label"), + "group=", + ch.get("group_id"), + ) + except Exception as e: + print("schedule ERR", e) + + try: + st = get("/api/youtube/relay/status") + print( + "relay auto=", + st.get("auto_enabled") or st.get("settings", {}).get("youtube_relay_auto"), + "running=", + st.get("running"), + "rows=", + len(st.get("rows") or st.get("monitors") or []), + ) + for row in st.get("rows") or st.get("monitors") or []: + nm = str(row.get("channel_name") or row.get("name") or "") + gid = str(row.get("group_id") or "") + if gid in seen or "asian" in nm.lower() or "nomadro" in nm.lower(): + print( + " mon", + nm or gid, + "biz=", + row.get("business_status"), + "push=", + row.get("is_pushing") or row.get("pushing"), + "neko_run=", + (row.get("neko") or {}).get("running"), + "studio=", + ((row.get("neko") or {}).get("studio") or {}).get("on_air"), + "err=", + (row.get("last_error") or row.get("error") or "")[:80], + ) + except Exception as e: + print("relay status ERR", e) + + try: + settings = get("/api/settings") + cfg = settings.get("settings") or settings + keys = [ + "youtube_relay_auto", + "youtube_relay_enabled", + "youtube_auto_relay", + "yt_relay_auto", + ] + for k in keys: + if k in cfg: + print("setting", k, "=", cfg.get(k)) + # print any youtube_relay* + for k, v in sorted(cfg.items()): + if "relay" in k.lower() and "youtube" in k.lower(): + if isinstance(v, (dict, list)): + continue + print("setting", k, "=", v) + except Exception as e: + print("settings ERR", e) + + +def ssh_probe(): + print("\n===== VPS host probe =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' ; " + "ss -lntp | grep -E ':920|:921' | head -20 ; " + "systemctl is-active douyinweb-api.service", + timeout=30, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + api("https://dylive.nomadro.com") + api("https://dy.nomadro.com") + ssh_probe() diff --git a/scripts/_probe_tm_hash_and_install.py b/scripts/_probe_tm_hash_and_install.py new file mode 100644 index 0000000..5638ea3 --- /dev/null +++ b/scripts/_probe_tm_hash_and_install.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Verify TM jsonImport hash match + try CDP install of .user.js.""" +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +# ensure userscript is served +ls -la /opt/douyinWEB/backend/neko/provisioning/ +# on ops1: hash check + CDP open install URL +docker exec douyinweb-ops-neko-1 python3 - <<'"'"'PY'"'"' +import json, hashlib, urllib.request, time + +def tm_sha256(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + +def tm_hash(value, seen=None): + if seen is None: + seen = [] + if value is None: + return tm_sha256("object:null") + if isinstance(value, dict): + ident = id(value) + if ident in seen: + raise ValueError("circular") + seen.append(ident) + try: + parts = [tm_hash(value[k], seen) for k in sorted(value)] + finally: + seen.pop() + return tm_sha256("".join(parts)) + if isinstance(value, list): + ident = id(value) + if ident in seen: + raise ValueError("circular") + seen.append(ident) + try: + parts = [tm_hash(item, seen) for item in value] + finally: + seen.pop() + return tm_sha256("".join(parts)) + if isinstance(value, bool): + return tm_sha256(f"boolean:{str(value).lower()}") + if isinstance(value, (int, float)) and not isinstance(value, bool): + return tm_sha256(f"number:{value}") + if isinstance(value, str): + return tm_sha256(f"string:{value}") + raise TypeError(type(value)) + +payload = json.loads(urllib.request.urlopen("http://127.0.0.1:18080/tampermonkey-provisioning.json", timeout=5).read()) +h = "1:" + tm_hash(payload) +pol = json.load(open("/etc/opt/chrome/policies/managed/policies.json")) +ph = pol["3rdparty"]["extensions"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]["jsonImport"][0]["hash"] +print("computed", h) +print("policy ", ph) +print("match", h == ph) +print("installAsSystemScripts", pol["3rdparty"]["extensions"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]["jsonImport"][0].get("installAsSystemScripts")) + +# list tabs / open install +tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +print("tabs_before", len(tabs)) +for t in tabs: + print("-", (t.get("url") or "")[:100]) + +# Open local userscript URL — TM should intercept +# First check if file is served +for url in [ + "http://127.0.0.1:18080/youtube-studio-auto-dismiss.user.js", + "http://127.0.0.1:18080/tampermonkey-provisioning.json", +]: + try: + r = urllib.request.urlopen(url, timeout=4) + print("GET", url, r.status, "len", len(r.read())) + except Exception as e: + print("GET fail", url, e) + +# new tab via CDP +try: + raw = urllib.request.urlopen("http://127.0.0.1:9222/json/new?http://127.0.0.1:18080/youtube-studio-auto-dismiss.user.js", timeout=5).read() + print("new_tab", raw[:300]) +except Exception as e: + print("new_tab_fail", e) + # fallback put + try: + req = urllib.request.Request("http://127.0.0.1:9222/json/new", method="PUT") + print("put_new", urllib.request.urlopen(req, timeout=5).read()[:200]) + except Exception as e2: + print("put_fail", e2) + +time.sleep(3) +tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +print("tabs_after", len(tabs)) +for t in tabs: + print("-", (t.get("title") or "")[:50], "|", (t.get("url") or "")[:120]) +PY +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_probe_yt_live_count.py b/scripts/_probe_yt_live_count.py new file mode 100644 index 0000000..00120e8 --- /dev/null +++ b/scripts/_probe_yt_live_count.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Probe YouTube live-map: who is counted as 在播 and why.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-20000:] if len(out) > 20000 else out, flush=True) + return code, out + + +c = ssh() +code, _ = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import asyncio, json, time +from app import youtube_live +from app.youtube_relay_pipeline import youtube_relay_pipeline as pipe +from app import youtube_neko as yn + +m = asyncio.run(youtube_live.build_live_map(force=True)) +print("live_count", m.get("live_count"), "checked_at_age", round(time.time()-float(m.get("checked_at") or 0),1), + "svc_error", m.get("svc_error"), "refreshing", m.get("refreshing")) + +live_rows=[] +for k,v in (m.get("entries") or {}).items(): + if not v.get("is_live"): + continue + st = v.get("studio") if isinstance(v.get("studio"), dict) else {} + live_rows.append({ + "key": k, + "title": v.get("title") or v.get("name") or v.get("label") or "", + "source": v.get("source"), + "assign_group_id": (str(v.get("assign_group_id") or "")[:8] or None), + "channel_id": (str(v.get("channel_id") or v.get("youtube_channel_id") or "")[:28] or None), + "studio": { + "on_air": st.get("on_air"), + "encoder_receiving": st.get("encoder_receiving"), + "encoder_lost": st.get("encoder_lost"), + "live_status": st.get("live_status"), + "health": st.get("health"), + "preparing_stream": st.get("preparing_stream"), + "age_sec": st.get("age_sec"), + "detect_source": st.get("detect_source"), + } if st else None, + "is_pushing_hint": v.get("is_pushing"), + }) + +print("LIVE_ENTRIES", len(live_rows)) +print(json.dumps(live_rows, ensure_ascii=False, indent=2)) + +st = pipe.status() +push=[] +for r in (st.get("groups") or []): + if r.get("is_pushing") or str(r.get("business_status") or "") in {"streaming","relay_slow","relay_starting"}: + snap=((r.get("neko") or {}).get("studio") or {}) + push.append({ + "name": r.get("name"), + "gid": str(r.get("group_id") or "")[:8], + "biz": r.get("business_status"), + "push": r.get("is_pushing"), + "neko": r.get("neko_instance_id"), + "studio_on_air": snap.get("on_air"), + "studio_status": snap.get("live_status"), + "studio_prep": snap.get("preparing_stream"), + "studio_recv": snap.get("encoder_receiving"), + "studio_lost": snap.get("encoder_lost"), + "studio_src": snap.get("detect_source"), + "studio_age": snap.get("age_sec"), + }) +print("RELAY_ACTIVE", json.dumps(push, ensure_ascii=False, indent=2)) + +inst = yn.list_instances(12, check_http=False) +running=[i for i in inst if i.get("running")] +print("NEKO_RUNNING", [(i.get("id"), i.get("status")) for i in running]) +for i in running[:8]: + nid=int(i.get("id") or 0) + try: + sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0) + print("cdp", nid, json.dumps({k:sig.get(k) for k in ( + "ok","live_status","on_air","preparing_stream","control_ready", + "encoder_receiving","encoder_lost","health","session_live" + )}, ensure_ascii=False)) + except Exception as e: + print("cdp_err", nid, e) +PY +""", +) +c.close() +raise SystemExit(code) diff --git a/scripts/_probe_yt_svc_basic.py b/scripts/_probe_yt_svc_basic.py new file mode 100644 index 0000000..fd3a445 --- /dev/null +++ b/scripts/_probe_yt_svc_basic.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +"""Ask youtube-svc getBasicInfo for studio video ids.""" +import json +import sys +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, urllib.request +vids=["PF16pG4VmSk","XW-3kA3XdfI","zblaCyR1AY8","aG0zIkmCJ2E","1cQY6jHytxQ","L1sF_kZvzIk"] +for vid in vids: + for path in ["/video/%s" % vid, "/basic/%s" % vid, "/info/%s" % vid]: + try: + raw=urllib.request.urlopen("http://127.0.0.1:8020"+path, timeout=40).read().decode() + print(vid, path, raw[:500]) + break + except Exception as e: + err=str(e) + if "404" in err: + continue + print(vid, path, "ERR", err[:120]) + break + else: + # try POST + try: + body=json.dumps({"url":"https://www.youtube.com/watch?v="+vid}).encode() + req=urllib.request.Request("http://127.0.0.1:8020/resolve", data=body, headers={"Content-Type":"application/json"}, method="POST") + print(vid, "resolve", urllib.request.urlopen(req, timeout=40).read()[:400]) + except Exception as e: + print(vid, "no endpoint", e) +# list routes from server +try: + print("root", urllib.request.urlopen("http://127.0.0.1:8020/", timeout=5).read()[:300]) +except Exception as e: + print("root", e) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=20) +stdin, stdout, stderr = c.exec_command("python3 -", timeout=120) +stdin.write(REMOTE) +stdin.channel.shutdown_write() +print(stdout.read().decode("utf-8", "replace")) +print(stderr.read().decode("utf-8", "replace")[-400:]) +c.close() diff --git a/scripts/_purge_covers_2d_dylive.py b/scripts/_purge_covers_2d_dylive.py new file mode 100644 index 0000000..2759dc2 --- /dev/null +++ b/scripts/_purge_covers_2d_dylive.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Run cover purge with systemd S3 env on dylive.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False) + cmd = r""" +set -e +# load same env as douyinweb-api +ENVFILE=$(mktemp) +systemctl show douyinweb-api -p Environment --value | tr ' ' '\n' | sed '/^$/d' > "$ENVFILE" +# also parse Environment= lines from unit +grep -E '^Environment=' /etc/systemd/system/douyinweb-api.service | sed 's/^Environment=//' | tr ' ' '\n' >> "$ENVFILE" || true +echo '---S3 env---' +grep -E '^DY_S3_' "$ENVFILE" | sort -u +cd /opt/douyinWEB/backend +set -a +# shellcheck disable=SC1090 +. "$ENVFILE" || true +set +a +export $(grep -E '^DY_S3_' "$ENVFILE" | sort -u | xargs -0 2>/dev/null || true) +# safer export +while IFS= read -r line; do + case "$line" in + DY_S3_*=*) export "$line" ;; + esac +done < <(grep -E '^DY_S3_' "$ENVFILE" | sort -u) +./.venv/bin/python - <<'PY' +import json, os +from app.config import settings +print('s3_enabled_cfg', settings.s3_enabled, settings.s3_endpoint, settings.s3_bucket) +print('env', {k:os.environ.get(k) for k in sorted(os.environ) if k.startswith('DY_S3_')}) +from app import s3_storage, db +print('s3_enabled()', s3_storage.s3_enabled()) +# list a few objects age stats first +client=None +try: + client=s3_storage._client() + resp=client.list_objects_v2(Bucket=settings.s3_bucket, Prefix='covers/', MaxKeys=5) + print('sample', [(o.get('Key'), str(o.get('LastModified'))) for o in (resp.get('Contents') or [])]) + # count roughly + n=0 + token=None + while True: + kw={'Bucket':settings.s3_bucket,'Prefix':'covers/','MaxKeys':1000} + if token: kw['ContinuationToken']=token + r=client.list_objects_v2(**kw) + n += len(r.get('Contents') or []) + if not r.get('IsTruncated'): break + token=r.get('NextContinuationToken') + if n>50000: break + print('approx_objects', n) +except Exception as e: + print('list_err', e) +cfg=db.get_settings_map() +r=s3_storage.purge_covers_older_than(keep_days=float(cfg.get('covers_s3_keep_days') or 2), max_delete=50000) +print(json.dumps(r, ensure_ascii=False)) +# second pass if truncated by limit +if r.get('deleted',0)>=50000: + r2=s3_storage.purge_covers_older_than(keep_days=2, max_delete=50000) + print('pass2', json.dumps(r2, ensure_ascii=False)) +PY +# seaweed vacuum via filer/master - try common ports +for u in \ + 'http://127.0.0.1:19333/vol/vacuum?garbageThreshold=0.01' \ + 'http://127.0.0.1:9333/vol/vacuum?garbageThreshold=0.01'; do + echo "try $u" + curl -sS -m 15 --http1.1 "$u" | head -c 400; echo +done +ss -lntp | grep -E 'weed|8333|9333|19333|18888' | head -20 +du -sh /data/seaweed +df -h / +rm -f "$ENVFILE" +""" + _i, o, e = c.exec_command(cmd, timeout=600, get_pty=True) + chan = o.channel + start = time.time() + while True: + if chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + if chan.exit_status_ready(): + while chan.recv_ready(): + sys.stdout.write(chan.recv(8192).decode("utf-8", "replace")) + sys.stdout.flush() + break + if time.time() - start > 580: + print("TIMEOUT", flush=True) + break + time.sleep(0.15) + print("\n[exit", chan.recv_exit_status(), "]", flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_push_fix_opsneko_chrome.py b/scripts/_push_fix_opsneko_chrome.py new file mode 100644 index 0000000..baada94 --- /dev/null +++ b/scripts/_push_fix_opsneko_chrome.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS = ("107.173.30.245", 4014, "eric", "4669805") +ROOT = "/opt/douyinWEB" +LOCAL = Path(__file__).resolve().parents[1] + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(*PHYS[:3], password=PHYS[3], timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + uploads = [ + ("backend/app/youtube_neko.py", f"{ROOT}/backend/app/youtube_neko.py"), + ("backend/app/ops_neko.py", f"{ROOT}/backend/app/ops_neko.py"), + ("backend/app/ops_neko_db.py", f"{ROOT}/backend/app/ops_neko_db.py"), + ("scripts/_remote_fix_opsneko_chrome.py", "/tmp/_remote_fix_opsneko_chrome.py"), + ] + for rel, dst in uploads: + with sftp.file("/tmp/_xfer_ops", "wb") as f: + f.write((LOCAL / rel).read_bytes()) + # stage then sudo install via shell + print("staged", rel, flush=True) + _i, o, e = c.exec_command( + f"echo '4669805' | sudo -S -p '' bash -lc \"cp /tmp/_xfer_ops {dst}; sed -i 's/\\r$//' {dst}; chmod 644 {dst}\"", + timeout=30, + ) + print((o.read() + e.read()).decode(), flush=True) + sftp.close() + + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc '" + f"cd {ROOT}/backend; " + "if [ -x ../.venv/bin/python ]; then PY=../.venv/bin/python; " + "elif [ -x .venv/bin/python ]; then PY=.venv/bin/python; " + "else PY=python3; fi; " + "$PY /tmp/_remote_fix_opsneko_chrome.py" + "'", + timeout=360, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + time.sleep(10) + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc '" + "docker exec douyinweb-ops-neko-1 env | grep -E \"^(ENV_USER|ENV_DISPLAY|USER|HOME|NEKO_LIVE|NEKO_MANAGED|NEKO_TAMPER|NEKO_BROWSER_RENDER)=\" | sort; " + "echo ---supervisor---; " + "docker exec douyinweb-ops-neko-1 supervisorctl status || true; " + "echo ---chrome-log---; " + "docker exec douyinweb-ops-neko-1 tail -50 /var/log/neko/google-chrome.log 2>/dev/null || true; " + "echo ---pgrep---; " + "docker exec douyinweb-ops-neko-1 pgrep -a chrome | head -8 || true; " + "docker exec douyinweb-ops-neko-1 pgrep -a Xvfb || true; " + "'", + timeout=60, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_quick_live_map.py b/scripts/_quick_live_map.py new file mode 100644 index 0000000..f5813aa --- /dev/null +++ b/scripts/_quick_live_map.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +"""Quick live-map verify after deploy; check API errors.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def run(port, user, pwd, label, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + script = r''' +import json, urllib.request, http.cookiejar, subprocess, time +print("health", urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=5).read()[:80]) +print(subprocess.getoutput("journalctl -u douyinweb-api -n 30 --no-pager | tail -30")) +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, method="POST") +op.open(req, timeout=10) +t0=time.time() +# non-force first +try: + raw=op.open("http://127.0.0.1:8014/api/youtube/live-map", timeout=30).read() + p=json.loads(raw) + print("cache live_count", p.get("live_count"), "source", p.get("source"), "dt", round(time.time()-t0,1)) +except Exception as e: + print("cache ERR", type(e).__name__, e) +t0=time.time() +try: + raw=op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=180).read() + p=json.loads(raw) + print("force live_count", p.get("live_count"), "source", p.get("source"), "dt", round(time.time()-t0,1)) + for k,v in sorted((p.get("entries") or {}).items()): + if v.get("is_live"): + print(" LIVE", k, v.get("source"), (v.get("title") or "")[:40], (v.get("live_url") or "")[:60]) +except Exception as e: + print("force ERR", type(e).__name__, e, "dt", round(time.time()-t0,1)) +''' + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_qmap.py", "w") as f: + f.write(script) + sftp.close() + cmd = f"echo '{pwd}' | sudo -S -p '' python3 /tmp/_qmap.py" + stdin, stdout, stderr = c.exec_command(cmd, timeout=240) + else: + stdin, stdout, stderr = c.exec_command("python3 -", timeout=240) + stdin.write(script) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-800:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys", sudo=True) diff --git a/scripts/_rearm_shorts_b_cooldown.py b/scripts/_rearm_shorts_b_cooldown.py new file mode 100644 index 0000000..5875f10 --- /dev/null +++ b/scripts/_rearm_shorts_b_cooldown.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +"""Re-arm Client B API cool-down with Pacific date so sync won't wipe it.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from datetime import datetime, timezone, timedelta +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +pt = datetime.fromtimestamp(time.time(), tz=timezone(timedelta(hours=-7))).strftime("%Y-%m-%d") + +REMOTE = f"""#!/bin/bash +set -euo pipefail +python3 <<'PY' +import sqlite3, json, time +conn = sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +raw = conn.execute("SELECT value FROM kv_settings WHERE key=?", ("shorts_yt_quota_by_profile",)).fetchone() +qmap = json.loads(raw[0]) if raw and raw[0] else {{}} +now = time.time() +pt = {pt!r} +until = now + 3600 +e = dict(qmap.get("B") or {{}}) +e["date"] = pt +e["blocked_until"] = until +e["quota_ntfy_at"] = now +e["count"] = max(int(e.get("count") or 0), 90) +qmap["B"] = e +conn.execute( + "INSERT INTO kv_settings(key,value) VALUES(?,?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + ("shorts_yt_quota_by_profile", json.dumps(qmap, ensure_ascii=False)), +) +conn.commit() +print("armed", qmap["B"]) +conn.close() +PY +systemctl restart douyinweb-api.service +sleep 5 +systemctl is-active douyinweb-api.service +""" + + +def deploy(label, host, port, user, pw, *, sudo): + print(f"===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dy_rearm_b.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_rearm_b.sh" if sudo else "bash /tmp/_dy_rearm_b.sh" + _, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) + print( + base, + "blocked=", st.get("upload_quota_blocked"), + "profiles=", st.get("upload_quota_blocked_profiles"), + "until=", st.get("upload_quota_blocked_until"), + "B=", next((p for p in (st.get("yt_quota_by_profile") or []) if p.get("id") == "B"), None), + ) + + +if __name__ == "__main__": + # Only dylive had recent B 429 spam + deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + pub("https://dylive.nomadro.com") + pub("https://dy.nomadro.com") diff --git a/scripts/_rebuild_phys_fe.py b/scripts/_rebuild_phys_fe.py new file mode 100644 index 0000000..0c3526b --- /dev/null +++ b/scripts/_rebuild_phys_fe.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +import paramiko + +REMOTE_SH = r"""#!/bin/bash +set -e +cd /opt/douyinWEB/frontend +npm run build >/tmp/fe_cont.log 2>&1 && echo FE_OK || { tail -40 /tmp/fe_cont.log; echo FE_FAIL; exit 1; } +systemctl restart douyinweb-yt douyinweb-api douyinweb-web +sleep 4 +systemctl is-active douyinweb-yt +systemctl is-active douyinweb-api +systemctl is-active douyinweb-web +for i in 1 2 3 4 5 6 7 8 9 10; do + code=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health=$code + if [ "$code" = "200" ]; then break; fi + sleep 2 +done +""" + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=30) +sftp = c.open_sftp() +with sftp.file("/tmp/_fe_phys.sh", "w") as f: + f.write(REMOTE_SH) +sftp.close() +_, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_fe_phys.sh", timeout=900) +print(o.read().decode("utf-8", "replace")) +err = e.read().decode("utf-8", "replace") +if err.strip(): + print(err[-800:]) +c.close() diff --git a/scripts/_recheck_live_map_now.py b/scripts/_recheck_live_map_now.py new file mode 100644 index 0000000..fae6a70 --- /dev/null +++ b/scripts/_recheck_live_map_now.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +"""Re-check live-map + yt_studio_samples on_air on both hosts.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, sqlite3, urllib.request, http.cookiejar, time +con=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +con.row_factory=sqlite3.Row +print("=== yt_studio_samples last 20 with on_air/enc ===") +try: + rows=list(con.execute(""" + select ts, name, group_id, youtube_channel_id, on_air, live_status, health, neko_ref, studio_url, detect_source + from yt_studio_samples s + left join yt_assign_groups g on g.id=s.group_id + order by s.ts desc limit 20 + """)) +except Exception: + rows=list(con.execute(""" + select ts, group_id, youtube_channel_id, on_air, live_status, health, neko_ref, studio_url, detect_source + from yt_studio_samples order by ts desc limit 20 + """)) +now=time.time() +for r in rows: + d=dict(r) + age=now-float(d.get("ts") or 0) + # handle weird future ts + if age < -1e6: age = float(d.get("ts") or 0) # leave raw + print( + "age", round(age,1) if isinstance(age,float) and abs(age)<1e7 else d.get("ts"), + "on_air", d.get("on_air"), + "st", d.get("live_status"), + "ref", d.get("neko_ref"), + "name", d.get("name") if "name" in d else "", + "url", (d.get("studio_url") or "")[:50], + ) + +# latest telemetry events +print("=== latest_studio_telemetry ===") +import sys, os +sys.path.insert(0,"/opt/douyinWEB/backend") +os.chdir("/opt/douyinWEB/backend") +from app import youtube_neko +for ev in youtube_neko.latest_studio_telemetry(limit=12): + pl=ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + sig=pl.get("signals") if isinstance(pl.get("signals"), dict) else {} + print( + "recv_at", ev.get("received_at"), + "ref", ev.get("neko_ref") or pl.get("neko_ref"), + "st", pl.get("live_status"), + "on_air", sig.get("on_air"), + "enc", sig.get("encoder_receiving"), + "url", (pl.get("url") or "")[:55], + ) + +cj=http.cookiejar.CookieJar() +op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, method="POST") +op.open(req, timeout=15) +p=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=120).read()) +print("live_count", p.get("live_count"), "source", p.get("source")) +for k,v in sorted((p.get("entries") or {}).items()): + if str(k).startswith("assign:"): + st=(v.get("studio") or {}) + print((" LIVE" if v.get("is_live") else " off "), (v.get("title") or k)[:28], v.get("source"), + "studio_on_air", st.get("on_air"), "enc", st.get("encoder_receiving"), "st", st.get("live_status"), + (v.get("live_url") or "")[:50]) +''' + + +def run(port, user, pwd, label, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port=port, username=user, password=pwd, timeout=25) + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_lm_now.py", "w") as f: + f.write(REMOTE) + sftp.close() + cmd = f"echo '{pwd}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_lm_now.py" + else: + cmd = "/opt/douyinWEB/backend/.venv/bin/python -" + stdin, stdout, stderr = c.exec_command(cmd, timeout=180) + if not sudo: + stdin.write(REMOTE) + stdin.channel.shutdown_write() + print("########", label, "########") + print(stdout.read().decode("utf-8", "replace")) + err = stderr.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-1500:]) + c.close() + + +if __name__ == "__main__": + run(22, "root", "Xiao4669805", "vps") + run(4014, "eric", "4669805", "phys", sudo=True) diff --git a/scripts/_recheck_neko8_tm.py b/scripts/_recheck_neko8_tm.py new file mode 100644 index 0000000..b1538e2 --- /dev/null +++ b/scripts/_recheck_neko8_tm.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + cmd = ( + "echo '4669805' | sudo -S -p '' bash -lc " + "'sleep 8; docker exec -i douyinweb-neko-8 python3 - <<\"PY\"\n" + "import os,json,urllib.request\n" + "mains=0;load=False;sw=-1\n" + "for pid in os.listdir(\"/proc\"):\n" + " if not pid.isdigit(): continue\n" + " try: raw=open(f\"/proc/{pid}/cmdline\",\"rb\").read()\n" + " except: continue\n" + " if not raw: continue\n" + " if b\"google-chrome\" in raw and b\"--type=\" not in raw and b\"crashpad\" not in raw and b\"browser-launch\" not in raw:\n" + " mains+=1\n" + " if b\"load-extension\" in raw and b\"dhdgff\" in raw: load=True\n" + "try:\n" + " tabs=json.loads(urllib.request.urlopen(\"http://127.0.0.1:9222/json/list\",timeout=3).read())\n" + " sw=sum(1 for t in tabs if t.get(\"type\")==\"service_worker\" and \"dhdgff\" in (t.get(\"url\") or \"\"))\n" + "except Exception as e:\n" + " sw=str(e)\n" + "print(\"neko-8\", \"mains\",mains,\"load\",load,\"tm_sw\",sw)\n" + "PY\n" + "curl -sS -m 5 -o /dev/null -w \"cn_neko3=%{http_code} cn_neko8=%{http_code}\\n\" " + "https://dy.nomadro.cn/neko/3/ https://dy.nomadro.cn/neko/8/'" + ) + # simpler via sftp script + sftp = c.open_sftp() + with sftp.file("/tmp/_recheck_n8.sh", "w") as f: + f.write( + """#!/bin/bash +sleep 5 +docker exec -i douyinweb-neko-8 python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1 +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception as e: + sw=repr(e) +print("neko-8", "mains", mains, "load", load, "tm_sw", sw) +PY +curl -sS -m 8 -o /dev/null -w 'cn_neko3=%{http_code}\\n' https://dy.nomadro.cn/neko/3/ +curl -sS -m 8 -o /dev/null -w 'cn_neko8=%{http_code}\\n' https://dy.nomadro.cn/neko/8/ +""" + ) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_recheck_n8.sh", + timeout=60, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_recover_dy_neko10_chrome.py b/scripts/_recover_dy_neko10_chrome.py new file mode 100644 index 0000000..0934d29 --- /dev/null +++ b/scripts/_recover_dy_neko10_chrome.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Diagnose + recover dy neko-10 chrome after launch sync.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +raw = ( + Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, +) +sftp = c.open_sftp() +with sftp.file("/tmp/browser-launch-lf.sh", "wb") as f: + f.write(raw) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== file check ===' +file /opt/douyinWEB/backend/neko/browser-launch.sh +head -1 /opt/douyinWEB/backend/neko/browser-launch.sh | od -c | head -1 +docker exec douyinweb-neko-10 sh -c 'file /etc/neko/browser-launch.sh; head -1 /etc/neko/browser-launch.sh | od -c | head -1; sh -n /etc/neko/browser-launch.sh && echo syntax_ok; grep -n js-flags /etc/neko/browser-launch.sh | head -1' + +echo '=== chrome log ===' +docker exec douyinweb-neko-10 sh -c 'tail -40 /var/log/neko/google-chrome.log 2>/dev/null; ls -la /var/log/neko/ 2>/dev/null | head' +docker exec douyinweb-neko-10 sh -c 'tail -40 /var/log/supervisor/google-chrome*.log 2>/dev/null; ls /var/log/supervisor/ 2>/dev/null' + +echo '=== rewrite inode + start ===' +INO=$(docker exec douyinweb-neko-10 sh -c 'ls -li /etc/neko/browser-launch.sh' | awk '{print $1}') +MATCH=$(find /opt /root -xdev -inum "$INO" 2>/dev/null | head -1) +echo INO=$INO MATCH=$MATCH +if [ -n "$MATCH" ]; then + cat /tmp/browser-launch-lf.sh > "$MATCH" + chmod 755 "$MATCH" +fi +cat /tmp/browser-launch-lf.sh > /opt/douyinWEB/backend/neko/browser-launch.sh +chmod 755 /opt/douyinWEB/backend/neko/browser-launch.sh + +docker exec douyinweb-neko-10 sh -c ' +sh -n /etc/neko/browser-launch.sh && echo syntax_ok2 +rm -f /home/neko/.config/google-chrome/Singleton* /tmp/.com.google.Chrome* 2>/dev/null +# try run once manually to see error +timeout 8 /etc/neko/browser-launch.sh 2>&1 | tail -30 || true +supervisorctl start google-chrome +sleep 10 +supervisorctl status google-chrome +curl -sS -m 3 http://127.0.0.1:9222/json/version || echo no_devtools +python3 - < 16000 else out, flush=True) + return code, out + + +c = ssh() + +# Drop page caches only (safe); show top mem hogs excluding sing-box/frpp/wg +run( + c, + r""" +set +e +echo ===MEM_BEFORE=== +free -h +# sync + drop caches to relieve immediate pressure (not stopping services) +sync; echo 3 > /proc/sys/vm/drop_caches +sleep 1 +echo ===MEM_AFTER_DROP=== +free -h +echo ===TOP_RSS=== +ps -eo pid,user,rss,comm --sort=-rss | head -25 +echo ===NEKO7_STATS=== +docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}}' douyinweb-neko-7 +""", +) + +# Soft Chrome renderer recover inside container: SIGTERM chrome only, let supervisord/neko relaunch. +# Do NOT docker recreate / wipe profile. +run( + c, + r""" +set +e +echo ===SOFT_CHROME=== +# List chrome pids via /proc (no ps in image sometimes) +docker exec douyinweb-neko-7 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < $p/cmdline 2>/dev/null) + case "$cmd" in + *chrome*|*chromium*) echo "${p#/proc/} $cmd" | head -c 200; echo;; + esac +done' | head -40 + +# Graceful: kill chrome renderer/browser; neko entrypoint should restart browser +docker exec douyinweb-neko-7 sh -c 'pkill -TERM -f "/usr/bin/google-chrome|/usr/bin/chromium|chrome --type=gpu|chrome --type=renderer" 2>/dev/null; pkill -TERM chrome 2>/dev/null; true' +sleep 4 +docker exec douyinweb-neko-7 sh -c 'pgrep -a chrome 2>/dev/null | head -10 || echo no_chrome_yet' +# If still dead, ask neko open studio via our helper +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time +from app import youtube_neko as yn, yt_assign_db + +nid=7 +# wait CDP back +ok=False +for i in range(20): + try: + urls=yn._cdp_live_studio_urls(nid) + tabs=yn._cdp_fetch_tabs(nid) + pages=[t for t in tabs if (t.get("type") or "page")=="page"] + print("wait", i, "pages", len(pages), "live_urls", urls[:1]) + if pages: + ok=True + break + except Exception as e: + print("wait_err", i, e) + time.sleep(2) +print("cdp_ready", ok) + +# Find asian time_slot group bound to neko 7 +g=None +for row in yt_assign_db.list_groups(include_urls=False): + if int(row.get("neko_instance_id") or 0)==7: + g=row + print("group", row.get("name"), row.get("id"), row.get("youtube_channel_id")) + break +studio = "" +if g: + ycid=str(g.get("youtube_channel_id") or "").strip() + studio = yn.studio_live_control_url(ycid) if ycid else "" + # Prefer exact video livestreaming URL if telemetry/cdp had one + for t in yn._cdp_fetch_tabs(nid): + u=str(t.get("url") or "") + if "studio.youtube.com" in u and "livestreaming" in u: + studio=u + break +if not studio: + studio="https://studio.youtube.com/video/4dntxn9WM_Y/livestreaming" +print("open", studio[:120]) +# Activate or open Live tab (safe CDP) +r=yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio) +print("ensure_tab", r) +time.sleep(8) +# Reload once more for Aw Snap residue +py=''' +import json,urllib.request,base64,os,socket,struct,time +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read().decode()) +pages=[t for t in tabs if (t.get("type") or "page")=="page"] +live=[t for t in pages if "livestreaming" in (t.get("url") or "").lower()] +pick=(live or [None])[0] +print("tabs",[( (t.get("url") or "")[:100], (t.get("title") or "")[:40]) for t in pages]) +if not pick: raise SystemExit(0) +tid=pick["id"]; ws=pick.get("webSocketDebuggerUrl"); url=pick.get("url") +urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}",timeout=3).read() +def ws_connect(u): + hostport,path=u[5:].split("/",1); path="/"+path; host,port=hostport.split(":") + sock=socket.create_connection((host,int(port)),timeout=8) + key=base64.b64encode(os.urandom(16)).decode() + sock.sendall(f"GET {path} HTTP/1.1\\r\\nHost: {hostport}\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Key: {key}\\r\\nSec-WebSocket-Version: 13\\r\\n\\r\\n".encode()) + buf=b"" + while b"\\r\\n\\r\\n" not in buf: buf+=sock.recv(4096) + return sock +def ws_send(sock,payload): + data=json.dumps(payload).encode(); mask=os.urandom(4) + hdr=bytearray([0x81,0x80|len(data)]); hdr.extend(mask) + sock.sendall(bytes(hdr)+bytes(b^mask[i%4] for i,b in enumerate(data))) +sock=ws_connect(ws) +ws_send(sock,{"id":1,"method":"Page.reload","params":{"ignoreCache":True}}) +time.sleep(2) +ws_send(sock,{"id":2,"method":"Page.navigate","params":{"url":url}}) +time.sleep(1) +print("reloaded", url[:120]) +''' +code,out=yn._run(["docker","exec",yn._container_name(nid),"python3","-c",py], timeout=40) +print(out[-2000:]) +time.sleep(10) +sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0) +print("FINAL", json.dumps({k:sig.get(k) for k in ("ok","url","live_status","on_air","control_ready","preparing_stream","health","text","error")}, ensure_ascii=False)[:900]) +print("MEM_HINT") +PY +free -h +docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}} cpu={{.CPUPerc}}' douyinweb-neko-7 +""", +) + +c.close() +print("DONE", time.strftime("%H:%M:%S")) diff --git a/scripts/_recover_sites_no_neko.py b/scripts/_recover_sites_no_neko.py new file mode 100644 index 0000000..f013fb9 --- /dev/null +++ b/scripts/_recover_sites_no_neko.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Recover dy + dylive only. NEVER start Neko/docker containers.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +GUEST = ("107.173.30.245", 4014, "eric", "4669805") + + +def ssh(host, port, user, pw, tries=15): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + pw, + timeout=40, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print(f"ssh {host}:{port} ok try={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"ssh {host}:{port} retry {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(4) + raise SystemExit(f"ssh fail {host}:{port}: {last}") + + +def run(c, cmd, t=180, label=""): + print(f"\n[{label}]$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-6500:] if len(out) > 6500 else out, flush=True) + print(f"[{label}]→{code}", flush=True) + return code, out + + +def probe(): + print("\n=== PUBLIC ===", flush=True) + with httpx.Client(follow_redirects=False, timeout=20) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dylive.nomadro.com/youtube", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + ]: + try: + r = cl.get(u) + print(f"{u} -> {r.status_code} loc={(r.headers.get('location') or '')[:50]}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + + +def main() -> int: + v = ssh(*VPS) + try: + # 1) Ensure Docker/Neko stay DOWN (no containers started) + run( + v, + "systemctl stop docker.socket docker containerd 2>/dev/null || true; " + "pkill -9 -f dockerd 2>/dev/null || true; " + "pkill -9 -f containerd-shim 2>/dev/null || true; " + "pkill -9 chrome 2>/dev/null || true; " + "pkill -9 chromium 2>/dev/null || true; " + "sleep 2; free -h | head -2; uptime; " + "ps aux | grep -E '[c]hrome|[d]ockerd|[n]eko' | wc -l", + t=90, + label="stop-docker-neko", + ) + + # 2) Core site services only + run( + v, + "mkdir -p /etc/systemd/system/caddy.service.d; " + "printf '[Service]\\nTimeoutStartSec=300\\n' > /etc/systemd/system/caddy.service.d/timeout.conf; " + "systemctl daemon-reload; " + "systemctl reset-failed caddy douyinweb-api douyinweb-web 2>/dev/null || true; " + "systemctl start seaweed-master seaweed-volume seaweed-filer seaweed-s3 frpp nginx 2>/dev/null || true; " + "systemctl start douyinweb-pb douyinweb-yt; sleep 2; " + "systemctl start douyinweb-api; sleep 8; " + "systemctl start douyinweb-web; sleep 4; " + "systemctl start caddy; sleep 4; " + "systemctl is-active caddy nginx frpp douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb docker; " + "ss -lntp | grep -E ':(443|80|8014|4015|4014|8020)\\b' || true; " + "free -h | head -2; uptime", + t=320, + label="start-core", + ) + + run( + v, + "curl -sS -m 15 http://127.0.0.1:8014/api/health | head -c 280; echo; " + "curl -sS -m 12 -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/; " + "curl -sS -m 12 -o /dev/null -w 'yt=%{http_code}\\n' http://127.0.0.1:4015/youtube; " + "curl -sS -m 12 -o /dev/null -w 'caddy_dylive=%{http_code}\\n' -k -H 'Host: dylive.nomadro.com' https://127.0.0.1/api/health", + t=50, + label="local-check", + ) + + # 3) WG for dy.nomadro.com (edge only; do not touch Neko) + run( + v, + "systemctl start 'wg-quick@wg-dy' 2>/dev/null || true; " + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -16", + t=45, + label="wg-vps", + ) + finally: + v.close() + + # 4) Physical guest via FRP — start app only, no neko + try: + g = ssh(*GUEST) + try: + run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 2; " + "systemctl start douyinweb-api douyinweb-web; sleep 3; " + "wg show wg-dy | head -14; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 200; echo" + "'", + t=100, + label="guest", + ) + finally: + g.close() + except Exception as ex: + print(f"guest FRP unavailable: {ex}", flush=True) + + v = ssh(*VPS) + try: + run( + v, + "ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 12 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health; " + "systemctl is-active docker || true", + t=40, + label="tunnel-check", + ) + finally: + v.close() + + probe() + print("\nDONE recover (neko left stopped)", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_recreate_assign_neko_tm.py b/scripts/_recreate_assign_neko_tm.py new file mode 100644 index 0000000..85336cd --- /dev/null +++ b/scripts/_recreate_assign_neko_tm.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Force-recreate assign Nekos so bind mounts pick up new browser-launch/seed/policies inodes.""" +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +# Push latest assets again with in-place cat (same inode if possible), then recreate. +PUSH = r''' +set -e +ROOT=/opt/douyinWEB/backend/neko +# Prefer in-place overwrite if files exist +for pair in \ + "browser-launch.sh.tmfix:browser-launch.sh" \ + "policies.json.tmfix:policies/policies.json" \ + "Preferences.tmfix:tampermonkey-seed/Default/Preferences" \ + "manifest.json.tmfix:tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" +do + src="/tmp/${pair%%:*}" + dst="$ROOT/${pair##*:}" + if [ -f "$dst" ]; then + cat "$src" > "$dst" + else + mkdir -p "$(dirname "$dst")" + cp -f "$src" "$dst" + fi +done +chmod 755 "$ROOT/browser-launch.sh" +# Ensure seed tree exists on host +ls -la "$ROOT/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" +ls -la "$ROOT/policies/policies.json" +md5sum "$ROOT/browser-launch.sh" | awk '{print "host_launch",$1}' +grep -c Offline "$ROOT/browser-launch.sh" | awk '{print "host_offline_hits",$1}' + +COMPOSE=/opt/douyinWEB/backend/data/neko/docker-compose.yml +# Remember which were running +RUNNING=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort || true) +echo "was_running: $RUNNING" + +cd /opt/douyinWEB/backend/data/neko +docker compose -f "$COMPOSE" up -d --force-recreate --no-start +echo "recreated_ok" + +# Start previously running +for name in $RUNNING; do + echo "start $name" + docker start "$name" || true +done +# If none were running (e.g. VPS), leave stopped — operator starts manually +sleep 18 + +for name in $RUNNING; do + echo "===== VERIFY $name =====" + docker exec "$name" bash -lc ' + echo offline_hits=$(grep -c Offline /etc/neko/browser-launch.sh || true) + echo seed=$(ls /etc/neko/tampermonkey-seed/Default/Extensions 2>/dev/null | head -1 || echo MISSING) + echo policy=$(test -f /etc/opt/chrome/policies/managed/policies.json && echo OK || echo MISSING) + md5sum /etc/neko/browser-launch.sh | awk "{print \"ctr_launch\",\$1}" + ' + docker exec "$name" python3 - <<'PY' +import json, os, re, urllib.request +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +pref=Path("/home/neko/.config/google-chrome/Default/Preferences") +e={} +if pref.exists(): + e=((json.loads(pref.read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("tm", e.get("state"), e.get("location"), e.get("from_webstore")) +print("ext", Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0/manifest.json").exists()) +sp=Path("/home/neko/.config/google-chrome/Default/Secure Preferences") +print("secure_bytes", sp.stat().st_size if sp.exists() else -1) +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00",b" ").decode() + except Exception: continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_ext", m.group(1) if m else None); found=True; break +if not found: print("load_ext NONE") +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +except Exception as ex: + print("cdp", type(ex).__name__); tabs=[] +print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or ""))) +print("tabs", len(tabs)) +PY +done +''' + + +def do_host(label: str, host: str, port: int, user: str, pw: str, use_sudo: bool) -> None: + print(f"\n########## {label} ##########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + files = { + "browser-launch.sh.tmfix": ROOT / "backend/neko/browser-launch.sh", + "policies.json.tmfix": ROOT / "backend/neko/policies/policies.json", + "Preferences.tmfix": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences", + "manifest.json.tmfix": ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json", + } + for name, path in files.items(): + with sftp.file(f"/tmp/{name}", "wb") as f: + f.write(path.read_bytes()) + print("up", name, flush=True) + with sftp.file("/tmp/_recreate_assign_neko.sh", "wb") as f: + f.write(PUSH.encode()) + sftp.close() + cmd = ( + f"echo {pw} | sudo -S -p '' bash /tmp/_recreate_assign_neko.sh" + if use_sudo + else "bash /tmp/_recreate_assign_neko.sh" + ) + _, o, e = c.exec_command(cmd, timeout=900) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +def main() -> None: + do_host("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True) + do_host("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) + + +if __name__ == "__main__": + main() diff --git a/scripts/_recreate_dylive_neko.py b/scripts/_recreate_dylive_neko.py new file mode 100644 index 0000000..aa28f8d --- /dev/null +++ b/scripts/_recreate_dylive_neko.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Force-recreate dylive assign Neko containers so :920x publish correctly.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + ) + return c + + +def run(c, cmd, t=300): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + return code, out + + +c = ssh() +run( + c, + r""" +set +e +cd /opt/douyinWEB/backend/data/neko +# Stop/remove stale containers that lack published ports +for id in 3 7 8; do + docker rm -f douyinweb-neko-$id 2>/dev/null +done +# Recreate via API start (writes compose + up) for enabled groups +CS=$(mktemp) +curl -sS -m 20 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null +python3 - <<'PY' +import json,urllib.request +cs=open('/tmp/neko_cookie.txt','w') +PY +# simpler: use curl cookie jar +GROUPS=$(curl -sS -m 20 -b "$CS" http://127.0.0.1:8014/api/youtube/assign/groups) +echo "$GROUPS" | python3 -c ' +import sys,json +rows=json.load(sys.stdin) +rows=rows if isinstance(rows,list) else rows.get("groups") or [] +for g in rows: + if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0)>0: + print(g["id"], int(g["neko_instance_id"]), (g.get("name") or "")[:30]) +' > /tmp/neko_enabled_groups.txt +cat /tmp/neko_enabled_groups.txt +while read -r GID NID NAME; do + echo "START $NID $NAME" + curl -sS -m 240 -b "$CS" -X POST "http://127.0.0.1:8014/api/youtube/assign/groups/${GID}/neko" \ + -H 'Content-Type: application/json' \ + -d '{"action":"start","enabled":true,"force_recreate":true}' | python3 -c ' +import sys,json +d=json.load(sys.stdin) +n=d.get("neko") or {} +print(" ->", n.get("status"), "running", n.get("running"), "ready", n.get("ready"), "studio", n.get("studio_url"), "err", d.get("detail") or d.get("error") or "") +' +done < /tmp/neko_enabled_groups.txt +sleep 3 +echo '--- docker ports ---' +docker ps --format '{{.Names}} {{.Status}} {{.Ports}}' | grep douyinweb-neko +echo '--- ss 920 ---' +ss -lntp | grep -E ':(920[0-7])\b' | head +for p in 9200 9202 9206; do + curl -sS -m 5 -o /dev/null -w "p$p=%{http_code}\n" http://127.0.0.1:$p/ || echo p$p=fail +done +rm -f "$CS" +""", + 300, +) +c.close() + +with httpx.Client(follow_redirects=False, timeout=25) as cl: + for u in [ + "https://dylive.nomadro.com/neko/3/", + "https://dylive.nomadro.com/neko/7/", + "https://dy.nomadro.com/neko/1/", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(u) + print(f"{r.status_code} {u}", flush=True) + except Exception as ex: + print(f"ERR {u} {ex}", flush=True) +print("DONE", flush=True) diff --git a/scripts/_reinstall_dy_nomadro_fresh.py b/scripts/_reinstall_dy_nomadro_fresh.py new file mode 100644 index 0000000..9046362 --- /dev/null +++ b/scripts/_reinstall_dy_nomadro_fresh.py @@ -0,0 +1,562 @@ +#!/usr/bin/env python3 +"""Full wipe + reinstall current douyinWEB on 108.174.50.68 (dy.nomadro.live).""" +from __future__ import annotations + +import os +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "108.174.50.68" +USER = "root" +PASSWORD = "Xiao4669805" +DOMAIN = "dy.nomadro.live" +ADMIN_USER = "hackrobot" +ADMIN_PASS = "Xiao4669805@" +APP_DIR = "/opt/douyinWEB" +LOCAL_ROOT = Path(__file__).resolve().parents[1] + +WEB_PORT = 4015 +API_PORT = 8014 +PB_PORT = 8092 +YT_PORT = 8020 +S3_PORT = 8333 +PUBLIC_BASE = f"https://{DOMAIN}" + +SKIP_DIRS = { + ".git", + "node_modules", + ".next", + "__pycache__", + ".venv", + "venv", + "backend/data/covers", + "backend/data/clips", + "backend/data/monitor.db", + "backend/data/monitor.db-shm", + "backend/data/monitor.db-wal", + "pb/pb_data", + "scripts/_audit", + "agent-transcripts", + ".cursor", + "desktop", # not needed on VPS web deploy +} +SKIP_EXTS = {".pyc", ".pyo"} + + +def should_skip(rel: str) -> bool: + parts = Path(rel).parts + for i in range(len(parts)): + sub = "/".join(parts[: i + 1]) + if sub in SKIP_DIRS or parts[i] in SKIP_DIRS: + return True + if rel.endswith(tuple(SKIP_EXTS)): + return True + if "scripts/_audit" in rel.replace("\\", "/"): + return True + # skip huge one-off probe outputs + if rel.startswith("scripts/_") and rel.endswith((".txt", ".out", ".log")): + return True + return False + + +def make_tarball() -> Path: + tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) + tmp.close() + tar_path = Path(tmp.name) + print(f"[pack] {LOCAL_ROOT} -> {tar_path}", flush=True) + n = 0 + with tarfile.open(tar_path, "w:gz") as tar: + for root, dirs, files in os.walk(LOCAL_ROOT): + dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".git")] + for name in files: + full = Path(root) / name + rel = full.relative_to(LOCAL_ROOT).as_posix() + if should_skip(rel): + continue + tar.add(full, arcname=rel) + n += 1 + print(f"[pack] files={n} size={tar_path.stat().st_size / 1024 / 1024:.1f} MB", flush=True) + return tar_path + + +WIPE_SH = r"""#!/usr/bin/env bash +set -euo pipefail +log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; } + +log "STOP old douyinweb stack" +systemctl stop douyinweb-web douyinweb-api douyinweb-yt douyinweb-pb \ + douyinweb-s3 douyinweb-sw-filer douyinweb-sw-volume douyinweb-sw-master \ + douyinweb-yt-slot-watch douyinweb-yt-viz-api douyinweb-yt-viz-recorder 2>/dev/null || true +systemctl disable douyinweb-web douyinweb-api douyinweb-yt douyinweb-pb \ + douyinweb-s3 douyinweb-sw-filer douyinweb-sw-volume douyinweb-sw-master \ + douyinweb-yt-slot-watch douyinweb-yt-viz-api douyinweb-yt-viz-recorder 2>/dev/null || true + +log "REMOVE old Neko containers (keep docker engine)" +if command -v docker >/dev/null 2>&1; then + ids=$(docker ps -aq --filter name=douyinweb-neko || true) + if [ -n "${ids:-}" ]; then + docker rm -f $ids || true + fi + # drop compose project leftovers + rm -rf /opt/douyinWEB/backend/neko-runtime /opt/douyinWEB/backend/data/neko 2>/dev/null || true +fi + +log "DELETE old app tree + runtime data" +rm -rf /opt/douyinWEB +rm -rf /data/douyinweb-seaweed +mkdir -p /data/douyinweb-seaweed/{master,volume,filer} + +log "REMOVE obsolete unit extras / stop page" +rm -f /etc/systemd/system/douyinweb-yt-slot-watch.service \ + /etc/systemd/system/douyinweb-yt-viz-api.service \ + /etc/systemd/system/douyinweb-yt-viz-recorder.service +rm -rf /etc/systemd/system/douyinweb-api.service.d \ + /etc/systemd/system/douyinweb-web.service.d +rm -rf /var/www/dy-stopped +systemctl daemon-reload + +# Keep /etc/douyinweb.env (DOMAIN/ADMIN/SESSION/S3 secrets) — regenerate missing keys only later. +log "WIPE done" +df -h / +""" + + +# Reuse deploy bootstrap body from _deploy_dy_nomadro.py (extract+build+nginx+ssl) +BOOTSTRAP_SH = r"""#!/usr/bin/env bash +set -euo pipefail + +DOMAIN="__DOMAIN__" +ADMIN_USER="__ADMIN_USER__" +ADMIN_PASS="__ADMIN_PASS__" +APP_DIR="__APP_DIR__" +PUBLIC_BASE="__PUBLIC_BASE__" +WEB_PORT="__WEB_PORT__" +API_PORT="__API_PORT__" +PB_PORT="__PB_PORT__" +YT_PORT="__YT_PORT__" +S3_PORT="__S3_PORT__" +SW_MASTER_PORT=19333 +SW_VOLUME_PORT=18080 +SW_FILER_PORT=18888 +PB_VER=0.25.8 +WEED_VER=3.80 +S3_ACCESS=douyin +S3_BUCKET=douyin-covers +PB_ADMIN_EMAIL="${ADMIN_USER}@${DOMAIN}" +ENV_FILE=/etc/douyinweb.env + +log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; } + +export DEBIAN_FRONTEND=noninteractive +log "ensure packages" +apt-get update -y +apt-get install -y --no-install-recommends \ + git curl unzip ca-certificates ffmpeg \ + python3 python3-venv python3-pip \ + nginx certbot python3-certbot-nginx + +if ! command -v node >/dev/null 2>&1 || [ "$(node -v | tr -d v | cut -d. -f1)" -lt 18 ]; then + curl -fsSL https://deb.nodesource.com/setup_20.x | bash - + apt-get install -y nodejs +fi +node -v +python3 --version +ffmpeg -version | head -1 + +if [ ! -f "$ENV_FILE" ]; then + SESSION_SECRET=$(openssl rand -hex 24) + S3_SECRET=$(openssl rand -hex 18) + cat >"$ENV_FILE" </etc/nginx/conf.d/dy-nomadro-live.conf <<'NGX' +server { + listen 80; + server_name __DOMAIN__; + client_max_body_size 200m; + + location ^~ /api/ { + proxy_pass http://127.0.0.1:__API_PORT__; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + } + # files only — do not proxy the /covers page (Next) + location ^~ /covers/ { + proxy_pass http://127.0.0.1:__API_PORT__; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + location ^~ /_/ { + proxy_pass http://127.0.0.1:__PB_PORT__; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + } + location ^~ /douyin-covers/ { + proxy_pass http://127.0.0.1:__S3_PORT__; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + client_max_body_size 200m; + } + location / { + proxy_pass http://127.0.0.1:__WEB_PORT__; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 60s; + } +} +NGX +sed -i "s/__DOMAIN__/${DOMAIN}/g; s/__API_PORT__/${API_PORT}/g; s/__PB_PORT__/${PB_PORT}/g; s/__S3_PORT__/${S3_PORT}/g; s/__WEB_PORT__/${WEB_PORT}/g" \ + /etc/nginx/conf.d/dy-nomadro-live.conf + +nginx -t +systemctl reload nginx + +log "certbot ssl (reuse existing cert if present)" +certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email --redirect || true +nginx -t && systemctl reload nginx + +log "sync admin" +cd "$APP_DIR/backend" +.venv/bin/python -c "from app.session_auth import ensure_default_admin_credentials; ensure_default_admin_credentials(); from app.session_auth import get_admin_credentials; u,h=get_admin_credentials(); print('admin', u)" + +# ensure empty rooms +.venv/bin/python - <<'PY' +from app import db +n=len(db.list_rooms() if hasattr(db,'list_rooms') else []) +print('rooms_count', n) +PY + +log "verify" +sleep 3 +systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-yt douyinweb-s3 || true +curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 400; echo +curl -sS -o /dev/null -w "web:%{http_code}\n" "http://127.0.0.1:${WEB_PORT}/login" || true +curl -sS -o /dev/null -w "pub:%{http_code}\n" --max-time 25 "${PUBLIC_BASE}/login" || true +echo "DONE ${PUBLIC_BASE}" +""" + + +def run_script(client: paramiko.SSHClient, content: str, remote: str, timeout: int = 3600) -> int: + sftp = client.open_sftp() + with sftp.file(remote, "w") as f: + f.write(content) + sftp.chmod(remote, 0o755) + sftp.close() + chan = client.get_transport().open_session() + chan.settimeout(timeout) + chan.get_pty(width=200, height=50) + chan.exec_command(f"bash {remote}") + while True: + if chan.recv_ready(): + print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True) + if chan.recv_stderr_ready(): + print(chan.recv_stderr(65535).decode("utf-8", "replace"), end="", flush=True) + if chan.exit_status_ready() and not chan.recv_ready() and not chan.recv_stderr_ready(): + break + time.sleep(0.3) + while chan.recv_ready(): + print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True) + return chan.recv_exit_status() + + +def main() -> int: + print("=== pack current source ===", flush=True) + tar_path = make_tarball() + + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + print(f"connecting {HOST}...", flush=True) + client.connect(HOST, 22, USER, PASSWORD, timeout=45, allow_agent=False, look_for_keys=False) + + print("=== WIPE old install ===", flush=True) + code = run_script(client, WIPE_SH, "/tmp/wipe_dy_nomadro.sh", timeout=300) + if code != 0: + print(f"wipe failed: {code}", flush=True) + return code + + print("=== upload tarball ===", flush=True) + sftp = client.open_sftp() + sftp.put(str(tar_path), "/tmp/douyinweb_deploy.tar.gz") + sftp.close() + os.unlink(tar_path) + + sh = ( + BOOTSTRAP_SH.replace("__DOMAIN__", DOMAIN) + .replace("__ADMIN_USER__", ADMIN_USER) + .replace("__ADMIN_PASS__", ADMIN_PASS) + .replace("__APP_DIR__", APP_DIR) + .replace("__PUBLIC_BASE__", PUBLIC_BASE) + .replace("__WEB_PORT__", str(WEB_PORT)) + .replace("__API_PORT__", str(API_PORT)) + .replace("__PB_PORT__", str(PB_PORT)) + .replace("__YT_PORT__", str(YT_PORT)) + .replace("__S3_PORT__", str(S3_PORT)) + ) + print("=== bootstrap fresh install ===", flush=True) + code = run_script(client, sh, "/tmp/bootstrap_dy_nomadro_fresh.sh", timeout=3600) + client.close() + print(f"\n=== exit {code} ===", flush=True) + print(f"URL: {PUBLIC_BASE}/", flush=True) + print(f"Login: {ADMIN_USER} / {ADMIN_PASS}", flush=True) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_remote_fix_opsneko_chrome.py b/scripts/_remote_fix_opsneko_chrome.py new file mode 100644 index 0000000..aa8a382 --- /dev/null +++ b/scripts/_remote_fix_opsneko_chrome.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Run on physical: rewrite ops compose + force recreate with Chrome env.""" +from __future__ import annotations + +import sys + +sys.path.insert(0, "/opt/douyinWEB/backend") + +from app import ops_neko +from app import ops_neko_db + +max_slot = max(ops_neko_db.max_slot(), 1) +text = ops_neko._render_compose(max_slot) +ops_neko._compose_path().write_text(text, encoding="utf-8") +print("ENV_USER", "ENV_USER" in text) +print("LIVE_OPS", "NEKO_LIVE_OPS_EXTENSION" in text) +print("\n".join(text.splitlines()[:60])) +was = {i for i in range(1, max_slot + 1) if ops_neko._container_running(i)} +was.add(1) +print("resume", sorted(was)) +print(ops_neko.sync_compose(start_slots=was, force_recreate=True)) diff --git a/scripts/_remote_fix_opsneko_tm_ext.sh b/scripts/_remote_fix_opsneko_tm_ext.sh new file mode 100644 index 0000000..c98e3ed --- /dev/null +++ b/scripts/_remote_fix_opsneko_tm_ext.sh @@ -0,0 +1,132 @@ +#!/bin/bash +# Diagnose + force-repair Tampermonkey EXTENSION on ops-neko 1/2. +set -u +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +SEED=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/$EXT + +echo "===== SEED =====" +ls -la "$SEED" || true +python3 - <<'PY' +import json +from pathlib import Path +seed=Path("/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo") +ms=list(seed.glob("*/manifest.json")) +print("seed_manifests", ms) +for m in ms: + d=json.load(open(m)) + print(m.parent.name, "mv", d.get("manifest_version"), "ver", d.get("version")) + for rel in ["background.html","background.js","extension.js","manifest.json"]: + p=m.parent/rel + print(" ", rel, p.exists(), p.stat().st_size if p.exists() else 0) +PY + +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== DIAG $name =====" + docker exec "$name" python3 - <<'PY' +import json +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +base=Path("/home/neko/.config/google-chrome/Default") +for pref_name in ("Preferences","Secure Preferences"): + p=base/pref_name + print("==", pref_name, "exists", p.exists()) + if not p.exists(): + continue + try: + d=json.loads(p.read_text()) + except Exception as e: + print(" parse_fail", e) + continue + e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} + print(" state", e.get("state"), "path", e.get("path"), "loc", e.get("location")) + print(" disable_reasons", e.get("disable_reasons")) + print(" from_webstore", e.get("from_webstore")) + mf=e.get("manifest") if isinstance(e.get("manifest"), dict) else {} + print(" mf_ver", mf.get("version"), "mf_name", mf.get("name")) +root=base/"Extensions"/ext +print("ext_dir", root.exists()) +if root.exists(): + for m in sorted(root.glob("*/manifest.json")): + d=json.load(open(m)) + print(" installed", m.parent.name, "mv", d.get("manifest_version"), "ver", d.get("version")) + missing=[rel for rel in ("background.html","background.js","extension.js") if not (m.parent/rel).exists()] + print(" missing", missing or "none") +PY + + echo "===== REPAIR $name =====" + docker exec "$name" supervisorctl stop google-chrome || true + sleep 2 + docker exec "$name" python3 - <<'PY' +import json, shutil +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +base=Path("/home/neko/.config/google-chrome/Default") +seed=Path("/etc/neko/tampermonkey-seed/Default/Extensions")/ext +ext_dst=base/"Extensions"/ext +for p in (ext_dst, base/"Local Extension Settings"/ext, base/"Managed Extension Settings"/ext): + if p.exists(): + shutil.rmtree(p, ignore_errors=True) + print("removed", p) +base.joinpath("Extensions").mkdir(parents=True, exist_ok=True) +if not seed.exists(): + raise SystemExit("NO_SEED_MOUNT") +shutil.copytree(seed, ext_dst) +print("seeded", ext_dst, "versions", [x.name for x in ext_dst.iterdir() if x.is_dir()]) +versions=sorted([p.name for p in ext_dst.iterdir() if p.is_dir() and (p/"manifest.json").is_file()]) +chosen=versions[-1] if versions else "" +manifest={} +if chosen: + manifest=json.loads((ext_dst/chosen/"manifest.json").read_text()) +entry={ + "state": 1, + "path": f"{ext}/{chosen}" if chosen else ext, + "location": 4, + "manifest": manifest, + "was_installed_by_default": False, + "from_webstore": False, +} +for pref_name in ("Preferences", "Secure Preferences"): + pref=base/pref_name + d={} + if pref.exists(): + try: + d=json.loads(pref.read_text()) + except Exception: + d={} + settings=d.setdefault("extensions", {}).setdefault("settings", {}) + cur=dict(settings.get(ext) or {}) + cur.update(entry) + cur.pop("disable_reasons", None) + settings[ext]=cur + pref.write_text(json.dumps(d, separators=(",", ":")), encoding="utf-8") + print("patched", pref_name, cur.get("path"), "state", cur.get("state")) +PY + docker exec "$name" bash -lc "chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences /home/neko/.config/google-chrome/Default/Secure\ Preferences 2>/dev/null || true" + docker exec "$name" supervisorctl start google-chrome +done + +echo waiting +sleep 15 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== VERIFY $name =====" + docker exec "$name" python3 - <<'PY' +import json +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +base=Path("/home/neko/.config/google-chrome/Default") +d=json.loads((base/"Preferences").read_text()) +e=((d.get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("state", e.get("state"), "path", e.get("path"), "disable", e.get("disable_reasons")) +root=base/"Extensions"/ext +print("ext_ok", root.exists(), "versions", [x.name for x in root.iterdir()] if root.exists() else []) +mf=root.joinpath(str(e.get("path","")).split("/")[-1], "manifest.json") if e.get("path") else None +if mf and mf.exists(): + print("manifest_ok", mf, json.load(open(mf)).get("version")) +else: + print("manifest_missing", mf) +PY + docker exec "$name" supervisorctl status google-chrome +done +echo DONE diff --git a/scripts/_remote_nomadvlog_diag.py b/scripts/_remote_nomadvlog_diag.py new file mode 100644 index 0000000..4c954cb --- /dev/null +++ b/scripts/_remote_nomadvlog_diag.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +import json +import time +import sqlite3 +import datetime +import sys + +DB = "/opt/douyinWEB/backend/data/monitor.db" +BJ = datetime.timezone(datetime.timedelta(hours=8)) +conn = sqlite3.connect(DB) +conn.row_factory = sqlite3.Row + + +def bj(ts): + try: + return datetime.datetime.fromtimestamp(float(ts or 0), BJ).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + return str(ts) + + +def cols(table): + return [r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()] + + +rows = conn.execute( + "SELECT id,name,category,enabled,neko_instance_id,youtube_channel_id FROM yt_assign_groups WHERE lower(name) LIKE '%nomadvlog%'" +).fetchall() +print("GROUPS", [dict(r) for r in rows]) +gids = [r["id"] for r in rows] +gid = gids[0] +print("events cols", cols("events")) +print("yt_relay_states cols", cols("yt_relay_states")) +print("yt_relay_sessions cols", cols("yt_relay_sessions")) +print("sessions cols", cols("sessions")[:30]) + +st = conn.execute("SELECT * FROM yt_relay_states WHERE group_id=?", (gid,)).fetchone() +print("\n==== STATE ====") +if st: + d = dict(st) + for k in sorted(d.keys()): + if k == "recent_log": + continue + print(f" {k}={d.get(k)}") + log = d.get("recent_log") or "" + if isinstance(log, str) and log.strip().startswith("["): + try: + log = json.loads(log) + except Exception: + pass + if isinstance(log, list): + print("recent_log:") + for line in log[-60:]: + print(" ", line) + else: + print("recent_log_raw", str(log)[-2500:]) +else: + print("NO STATE ROW") + +# relay sessions history +print("\n==== yt_relay_sessions ====") +try: + rs = conn.execute( + "SELECT * FROM yt_relay_sessions WHERE group_id=? ORDER BY rowid DESC LIMIT 40", + (gid,), + ).fetchall() + print("count", len(rs)) + for r in rs: + d = dict(r) + print({k: d.get(k) for k in d if k != "recent_log"}) +except Exception as e: + print("err", e) + +# events schema adaptive +ecols = set(cols("events")) +ts_col = "created_at" if "created_at" in ecols else ("ts" if "ts" in ecols else None) +print("\n==== EVENTS ts_col", ts_col, "====") +if ts_col: + ev = conn.execute( + f""" + SELECT * FROM events + WHERE {ts_col} > ? + AND ( + message LIKE '%nomadvlog%' + OR message LIKE '%YouTube 开播%' + OR message LIKE '%YouTube 停播%' + OR IFNULL(room_pk,'') = ? + OR IFNULL(meta,'') LIKE ? + ) + ORDER BY {ts_col} DESC LIMIT 150 + """, + (time.time() - 36 * 3600, gid, f"%{gid}%"), + ).fetchall() + print("events", len(ev)) + open_n = close_n = 0 + for e in ev: + d = dict(e) + msg = d.get("message") or "" + tsv = d.get(ts_col) + print(bj(tsv), d.get("kind"), msg[:150]) + if "开播" in msg and ("nomadvlog" in msg.lower() or d.get("room_pk") == gid): + open_n += 1 + if "停播" in msg and ("nomadvlog" in msg.lower() or d.get("room_pk") == gid): + close_n += 1 + print("FLAP open", open_n, "close", close_n) + +# youtube channel groups table? for monitor +print("\n==== channel_groups / yt status ====") +for t in ("channel_groups", "youtube_channels", "yt_channels"): + if t in {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}: + print("table", t, cols(t)[:25]) + +# settings +print("\n==== SETTINGS ====") +for k in [ + "youtube_relay_enabled", + "youtube_relay_time_slot_mode", + "youtube_relay_exclusive_live", + "youtube_relay_respect_schedule", + "youtube_relay_on_air_deadline_sec", +]: + row = conn.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone() + print(k, row["value"] if row else None) + +# schedule +print("\n==== SCHEDULE ====") +sys.path.insert(0, "/opt/douyinWEB/backend") +from app import yt_assign_db + +sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True) +print("keys", list(sched.keys())) +for c in sched.get("channels") or []: + if "nomadvlog" in str(c.get("name") or "").lower() or c.get("active"): + print(json.dumps(dict(c), ensure_ascii=False, default=str)[:1000]) + +# shorts channel same YT id? +print("\n==== shorts same UC ====") +uc = rows[0]["youtube_channel_id"] +sc = conn.execute( + "SELECT id,name,enabled,last_status,last_title,last_live_url FROM shorts_channels WHERE youtube_channel_id=?", + (uc,), +).fetchall() +print([dict(x) for x in sc]) + +conn.close() diff --git a/scripts/_remote_nomadvlog_run.sh b/scripts/_remote_nomadvlog_run.sh new file mode 100644 index 0000000..ac59dfe --- /dev/null +++ b/scripts/_remote_nomadvlog_run.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -e +/opt/douyinWEB/backend/.venv/bin/python /tmp/_dy_nv_diag.py +echo "===JOURNAL===" +journalctl -u douyinweb-api.service --since "24 hours ago" --no-pager 2>/dev/null \ + | grep -iE 'nomadvlog|45f9bd79|source_switch|outside_slot|invalid push|on_air|exclusive' \ + | tail -150 || true diff --git a/scripts/_repair_dy_edge_keep.py b/scripts/_repair_dy_edge_keep.py new file mode 100644 index 0000000..299a443 --- /dev/null +++ b/scripts/_repair_dy_edge_keep.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Repair dy.nomadro.com path: bounce wg-dy, ping physical, keep edge services up. + +Does NOT start nomadro/robook/tiktok-promo/xauto/ebook/hackrobot product stacks. +""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +GUEST = ("107.173.30.245", 4014, "eric", "4669805") +GUEST_SUDO = "4669805" + + +def ssh(host, port, user, pw, tries=10): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=60, banner_timeout=180, allow_agent=False, look_for_keys=False) + print(f"ssh ok {host}:{port} try={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"ssh retry {host}:{port} {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(5) + raise SystemExit(f"ssh failed {host}:{port}: {last}") + + +def run(c, cmd, t=120, label=""): + print(f"\n[{label}]$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-5000:] if len(out) > 5000 else out, flush=True) + print(f"[{label}]→ {code}", flush=True) + return code, out + + +def main() -> int: + v = ssh(*VPS) + + # Ensure edge stays up + run( + v, + "systemctl start caddy nginx frpp docker 'wg-quick@wg-dy'; " + "systemctl is-active caddy nginx frpp docker 'wg-quick@wg-dy'", + label="vps-edge", + ) + + # Bounce WG on VPS + run( + v, + "wg-quick down wg-dy 2>/dev/null || true; wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -25; ping -c 3 -W 3 10.8.0.2 | tail -5", + t=60, + label="vps-wg-bounce", + ) + + # Try FRP guest: bounce peer side too + try: + g = ssh(*GUEST) + run( + g, + f"echo '{GUEST_SUDO}' | sudo -S -p '' bash -lc '" + "wg show wg-dy | head -20; " + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 2; " + "wg show wg-dy | head -20; " + "ping -c 3 -W 3 10.8.0.1 | tail -5; " + "systemctl is-active douyinweb-api douyinweb-web || true; " + "systemctl start douyinweb-api douyinweb-web 2>/dev/null || true; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 200; echo" + "'", + t=90, + label="guest-wg", + ) + g.close() + except Exception as ex: + print(f"guest FRP path issue: {ex}", flush=True) + + # Re-check from VPS through tunnel + time.sleep(3) + run( + v, + "wg show wg-dy | head -20; " + "ping -c 4 -W 3 10.8.0.2 | tail -6; " + "curl -sS -m 12 -o /dev/null -w 'via_wg_api=%{http_code}\\n' http://10.8.0.2:8014/api/health; " + "curl -sS -m 12 -o /dev/null -w 'via_wg_web=%{http_code}\\n' http://10.8.0.2:4015/", + t=50, + label="vps-verify-tunnel", + ) + v.close() + + print("\n=== public ===", flush=True) + with httpx.Client(follow_redirects=False, timeout=30) as cl: + for url in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.com/login", + ]: + try: + r = cl.get(url) + print(f"{url} -> {r.status_code} loc={r.headers.get('location','')[:60]}", flush=True) + except Exception as ex: + print(f"{url} ERR {ex}", flush=True) + + print("DONE", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_repair_dylive_all_tm_scripts.py b/scripts/_repair_dylive_all_tm_scripts.py new file mode 100644 index 0000000..fcf681e --- /dev/null +++ b/scripts/_repair_dylive_all_tm_scripts.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Audit+repair empty Tampermonkey script stores on dylive (all profiles). No recreate.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(10): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set +e +TM=dhdgffkkebhmkfjojejmpbldmpobfkfo +BASE=/opt/douyinWEB/backend/data/neko/profiles +GOOD="" + +echo '=== audit all profiles ===' +for d in "$BASE"/*; do + [ -d "$d" ] || continue + id=$(basename "$d") + p="$d/Default/Local Extension Settings/$TM" + if [ ! -d "$p" ]; then + echo "id=$id NO_TM_DIR" + continue + fi + markers=$(grep -a -R -c "YouTube Studio Auto Dismiss" "$p" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}') + bytes=$(du -sb "$p" 2>/dev/null | awk '{print $1}') + echo "id=$id bytes=$bytes markers=$markers" + if [ "${markers:-0}" -gt 0 ] && [ "${bytes:-0}" -gt 10000 ]; then + if [ -z "$GOOD" ]; then GOOD="$p"; fi + fi +done +echo "GOOD_SRC=$GOOD" + +if [ -z "$GOOD" ]; then + echo 'FATAL: no good TM source on this host' + exit 2 +fi + +echo +echo '=== repair empty/missing ===' +for d in "$BASE"/*; do + [ -d "$d" ] || continue + id=$(basename "$d") + p="$d/Default/Local Extension Settings/$TM" + markers=$(grep -a -R -c "YouTube Studio Auto Dismiss" "$p" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}') + bytes=$(du -sb "$p" 2>/dev/null | awk '{print $1}') + need=0 + if [ ! -d "$p" ]; then need=1; fi + if [ "${markers:-0}" -lt 1 ]; then need=1; fi + if [ "${bytes:-0}" -lt 8000 ]; then need=1; fi + if [ "$need" != 1 ]; then + echo "OK id=$id" + continue + fi + echo "REPAIR id=$id (bytes=$bytes markers=$markers)" + name="douyinweb-neko-$id" + running=0 + if docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null | grep -q true; then + running=1 + docker exec "$name" supervisorctl stop google-chrome 2>/dev/null || true + sleep 1 + fi + mkdir -p "$(dirname "$p")" + ts=$(date +%s) + if [ -d "$p" ]; then mv "$p" "$p.bak-empty-$ts"; fi + cp -a "$GOOD" "$p" + rm -f "$p/LOCK" 2>/dev/null || true + # ownership: profile dirs usually 1000:1000 (neko) + chown -R 1000:1000 "$p" 2>/dev/null || true + if [ "$running" = 1 ]; then + docker exec "$name" sh -c 'rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null; chown -R neko:neko "/home/neko/.config/google-chrome/Default/Local Extension Settings/'"$TM"'" 2>/dev/null; rm -f "/home/neko/.config/google-chrome/Default/Local Extension Settings/'"$TM"'/LOCK"; supervisorctl start google-chrome' + sleep 6 + docker exec "$name" supervisorctl status google-chrome 2>/dev/null | head -1 + docker exec "$name" sh -c ' +python3 - <<"PY" +import os,re +p="/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +blob=b"" +for root,_,fs in os.walk(p): + for f in fs: + try: blob+=open(os.path.join(root,f),"rb").read() + except: pass +print(" live_blob",len(blob),"markers",len(re.findall(r"YouTube Studio Auto Dismiss", blob.decode("latin1","ignore")))) +PY +' + else + echo " (container not running — profile fixed for next start)" + fi +done + +echo +echo '=== also refresh seed Local Extension Settings from GOOD (so future seed_tampermonkey_storage works) ===' +SEED=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/$TM +mkdir -p "$(dirname "$SEED")" +# only refresh if seed lacks script markers +sm=$(grep -a -R -c "YouTube Studio Auto Dismiss" "$SEED" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}') +sb=$(du -sb "$SEED" 2>/dev/null | awk '{print $1}') +echo "seed_before markers=$sm bytes=$sb" +if [ "${sm:-0}" -lt 1 ]; then + ts=$(date +%s) + if [ -d "$SEED" ]; then mv "$SEED" "$SEED.bak-$ts"; fi + cp -a "$GOOD" "$SEED" + rm -f "$SEED/LOCK" + echo "seed_refreshed from GOOD" +fi +grep -a -R -c "YouTube Studio Auto Dismiss" "$SEED" 2>/dev/null | awk -F: '{s+=$2} END{print "seed_markers",s+0}' + +echo +echo '=== running fleet summary ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + docker exec "$name" sh -c ' +python3 - <<"PY" +import os,re,sys +p="/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +blob=b"" +for root,_,fs in os.walk(p): + for f in fs: + try: blob+=open(os.path.join(root,f),"rb").read() + except: pass +m=len(re.findall(r"YouTube Studio Auto Dismiss", blob.decode("latin1","ignore"))) +print(sys.argv[1], "tm_ok" if m>0 else "tm_EMPTY", "blob",len(blob),"markers",m) +PY +' "$name" +done +echo ALL_REPAIR_DONE +""", + timeout=300, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_repair_opsneko_tm.py b/scripts/_repair_opsneko_tm.py new file mode 100644 index 0000000..7c454b1 --- /dev/null +++ b/scripts/_repair_opsneko_tm.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Force-repair Tampermonkey userscript on ops-neko 1+2 (physical).""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +FILES = [ + "backend/neko/provisioning/youtube-studio-auto-dismiss.user.js", + "backend/neko/provisioning/tampermonkey-provisioning.json", + "backend/neko/policies/policies.json", + "backend/neko/browser-launch.sh", +] + + +def main() -> None: + # Refresh provisioning locally first + import subprocess + + subprocess.check_call( + [sys.executable, str(ROOT / "backend/neko/render_tampermonkey_provisioning.py"), "--write"], + cwd=str(ROOT), + ) + # Sync policy hash from render output + out = subprocess.check_output( + [sys.executable, str(ROOT / "backend/neko/render_tampermonkey_provisioning.py")], + cwd=str(ROOT), + text=True, + ) + print(out) + h = "" + for line in out.splitlines(): + if line.startswith("hash="): + h = line.split("=", 1)[1].strip() + if h: + pol = ROOT / "backend/neko/policies/policies.json" + import json + + data = json.loads(pol.read_text(encoding="utf-8")) + data["3rdparty"]["extensions"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]["jsonImport"][0]["hash"] = h + pol.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("policies hash ->", h) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + for rel in FILES: + tmp = f"/tmp/_tmfix_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write((ROOT / rel).read_bytes()) + dst = f"/opt/douyinWEB/{rel}" + cmd = ( + f"echo '4669805' | sudo -S -p '' bash -lc " + f"\"install -m 644 {tmp} {dst}; sed -i 's/\\r$//' {dst}; chmod +x /opt/douyinWEB/backend/neko/browser-launch.sh\"" + ) + c.exec_command(cmd, timeout=30)[1].read() + print("ok", rel, flush=True) + sftp.close() + + repair = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== repair $name =====" + docker exec "$name" supervisorctl stop google-chrome || true + sleep 2 + docker exec "$name" bash -lc " + P=/home/neko/.config/google-chrome/Default + rm -f \"\$P/Local Extension Settings/$EXT/LOCK\" 2>/dev/null || true + # Force clean re-import via managed jsonImport (LES often goes \"internal error\" after hard restart) + rm -rf \"\$P/Local Extension Settings/$EXT\" \"\$P/Managed Extension Settings/$EXT\" + mkdir -p \"\$P/Local Extension Settings\" \"\$P/Managed Extension Settings\" + chown -R neko:neko \"\$P/Local Extension Settings\" \"\$P/Managed Extension Settings\" + echo wiped_tm_storage + " + docker exec "$name" supervisorctl start google-chrome +done +echo waiting_import +sleep 18 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== verify $name =====" + docker exec "$name" bash -lc " + P=/home/neko/.config/google-chrome/Default + echo LES=\$(du -sh \"\$P/Local Extension Settings/$EXT\" 2>/dev/null | awk \"{print \\\$1}\") + echo MAN=\$(du -sh \"\$P/Managed Extension Settings/$EXT\" 2>/dev/null | awk \"{print \\\$1}\") + CNT=\$(grep -aR \"YouTube Studio Auto Dismiss\" \"\$P/Local Extension Settings/$EXT\" 2>/dev/null | wc -l) + echo SCRIPT_HITS=\$CNT + supervisorctl status google-chrome + " + docker exec "$name" python3 - <<'"'"'PY'"'"' +import json, urllib.request +try: + tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read()) +except Exception as e: + print("cdp", e) + raise SystemExit(0) +closed = 0 +for t in tabs: + u = (t.get("url") or "").lower() + if "tampermonkey.net/changelog" in u or "tampermonkey.net/installed" in u: + tid = t.get("id") + if tid: + try: + urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=3) + closed += 1 + except Exception: + pass +print("tabs", len(tabs), "closed_junk", closed) +for t in tabs[:12]: + print("-", (t.get("title") or "")[:40], "|", (t.get("url") or "")[:90]) +PY +done +' +""" + _i, o, e = c.exec_command(repair, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + print("DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_report_vps_services.py b/scripts/_report_vps_services.py new file mode 100644 index 0000000..26c8407 --- /dev/null +++ b/scripts/_report_vps_services.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Read-only inventory of dylive VPS services for operator review.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST = "107.173.30.245" +PASS = "Xiao4669805" + + +def connect(): + last = None + for i in range(15): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + PASS, + timeout=45, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected attempt={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"retry {i} {type(ex).__name__}: {ex}", flush=True) + time.sleep(6) + raise SystemExit(f"ssh failed: {last}") + + +def run(c, title: str, cmd: str, timeout: int = 90) -> str: + print(f"\n## {title}", flush=True) + print(f"$ {cmd}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + text = out[-15000:] if len(out) > 15000 else out + print(text if text.strip() else "(empty)", flush=True) + return out + + +def main() -> int: + c = connect() + try: + run(c, "host / load", "hostname; uptime; free -h; df -h / /var /opt 2>/dev/null | grep -v tmpfs") + run( + c, + "running systemd services", + "systemctl list-units --type=service --state=running --no-pager --no-legend", + ) + run( + c, + "enabled non-default-ish units", + "systemctl list-unit-files --type=service --state=enabled --no-pager --no-legend", + ) + run( + c, + "douyinweb / project units", + "systemctl list-units --all --no-pager 'douyinweb*' 'caddy*' 'nginx*' 'docker*' " + "'wg*' 'frp*' 'sing*' 'shellcrash*' 'clash*' 's3*' 'minio*' 'seaweed*' 2>/dev/null; " + "ls -la /etc/systemd/system/douyinweb* /etc/systemd/system/*neko* 2>/dev/null; " + "systemctl cat douyinweb-api 2>/dev/null | head -40", + ) + run( + c, + "docker containers", + "docker ps -a --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null", + timeout=60, + ) + run( + c, + "listening ports", + "ss -lntup 2>/dev/null | head -120", + ) + run( + c, + "top memory processes", + "ps aux --sort=-%mem | head -30", + ) + run( + c, + "top cpu processes", + "ps aux --sort=-%cpu | head -20", + ) + run( + c, + "caddy / nginx sites", + "command -v caddy nginx; " + "ls /etc/caddy 2>/dev/null; ls /etc/caddy/Caddyfile* 2>/dev/null; " + "(test -f /etc/caddy/Caddyfile && grep -E '^[a-zA-Z0-9.*_-]+' /etc/caddy/Caddyfile | head -40); " + "ls /etc/nginx/sites-enabled /www/server/panel/vhost/nginx 2>/dev/null | head -40; " + "systemctl is-active caddy nginx 2>/dev/null", + ) + run( + c, + "wireguard / frp / proxy hubs", + "wg show 2>/dev/null | head -80; " + "systemctl is-active 'wg-quick@*' frps frpc 2>/dev/null; " + "ls /etc/wireguard 2>/dev/null; " + "ps aux | grep -E '[f]rp|[s]ing-box|[c]lash|[s]hellcrash|[m]ihomo' | head -20", + ) + run( + c, + "project health quick", + "cd /opt/douyinWEB 2>/dev/null && git rev-parse --short HEAD && git status -sb; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 600; echo; " + "curl -sS -m 8 -o /dev/null -w 'public_health=%{http_code}\\n' https://dylive.nomadro.com/api/health || true", + timeout=40, + ) + run( + c, + "cron / timers", + "systemctl list-timers --all --no-pager | head -40; " + "crontab -l 2>/dev/null; ls /etc/cron.d 2>/dev/null", + ) + print("\nDONE inventory", flush=True) + return 0 + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_report_vps_services2.py b/scripts/_report_vps_services2.py new file mode 100644 index 0000000..375091e --- /dev/null +++ b/scripts/_report_vps_services2.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Quick follow-up: docker names + listen ports only.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(): + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + banner_timeout=120, + allow_agent=False, + look_for_keys=False, + ) + print("connected", i, flush=True) + return c + except Exception as ex: + print("retry", i, ex, flush=True) + time.sleep(5) + raise SystemExit("ssh fail") + + +def run(c, cmd, t=45): + print(f"\n$ {cmd}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + # read with channel timeout + chan = o.channel + chan.settimeout(t) + data = b"" + while True: + try: + chunk = chan.recv(8192) + if not chunk: + break + data += chunk + if len(data) > 20000: + break + except Exception: + break + err = b"" + try: + err = e.read(4096) + except Exception: + pass + print((data + err).decode("utf-8", "replace")[:18000], flush=True) + + +c = connect() +try: + run(c, "timeout 20 docker ps -a --format '{{.Names}}|{{.Status}}' 2>/dev/null | head -40", 30) + run(c, "timeout 15 ss -lnt | awk 'NR==1 || /LISTEN/' | head -60", 25) + run(c, "timeout 10 systemctl is-active douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb caddy nginx seaweed-s3 frpp 'wg-quick@wg-dy' sing-box 2>/dev/null; " + "cd /opt/douyinWEB && git rev-parse --short HEAD 2>/dev/null", 20) +finally: + c.close() +print("DONE", flush=True) diff --git a/scripts/_rescue_vps_api.py b/scripts/_rescue_vps_api.py new file mode 100644 index 0000000..6ae9e1c --- /dev/null +++ b/scripts/_rescue_vps_api.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_rescue_api.sh", "w") as f: + f.write( + r"""#!/bin/bash +systemctl status douyinweb-api --no-pager | head -30 +echo '---KILL---' +systemctl kill -s SIGKILL douyinweb-api 2>/dev/null || true +sleep 1 +systemctl reset-failed douyinweb-api || true +systemctl start douyinweb-api +sleep 4 +systemctl is-active douyinweb-api +curl -sS -m 5 -o /dev/null -w 'health=%{http_code}\n' http://127.0.0.1:8014/api/health || true +echo '---YT SVC---' +systemctl list-units --type=service --all | grep -iE 'youtube|yt-svc|innertube' || true +docker ps --format '{{.Names}} {{.Ports}}' | head -40 +ss -lntp | grep -E '8089|8099|8014' || true +""" + ) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_rescue_api.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_restart_nekos_remount_launch.py b/scripts/_restart_nekos_remount_launch.py new file mode 100644 index 0000000..0187383 --- /dev/null +++ b/scripts/_restart_nekos_remount_launch.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Restart Neko containers to remount browser-launch bind (profile volumes untouched).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def run_phys() -> None: + script = r"""#!/bin/bash +set -e +NAMES=$(docker ps --format '{{.Names}}' | grep -E 'douyinweb-(neko-|ops-neko-)' | sort) +echo "restarting:" $NAMES +for N in $NAMES; do + docker restart "$N" +done +echo wait... +sleep 35 +for N in $NAMES; do + lines=$(docker exec "$N" wc -l /etc/neko/browser-launch.sh 2>/dev/null | awk '{print $1}') + trap=$(docker exec "$N" grep -c on_supervisor_stop /etc/neko/browser-launch.sh 2>/dev/null || echo 0) + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1 +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw}") +PY +) + echo "$N lines=$lines trap=$trap $out" +done +curl -sS -m 8 -o /dev/null -w 'cn_neko3=%{http_code}\n' https://dy.nomadro.cn/neko/3/ || true +""" + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_restart_phys_nekos_remount.sh", "w") as f: + f.write(script) + sftp.close() + print("===== PHYSICAL =====") + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_restart_phys_nekos_remount.sh", + timeout=420, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def run_vps() -> None: + script = r"""#!/bin/bash +set -e +NAMES=$(docker ps --format '{{.Names}}' | grep -E 'douyinweb-neko-[0-9]+$' | sort) +echo "restarting:" $NAMES +for N in $NAMES; do + docker restart "$N" +done +sleep 30 +for N in $NAMES; do + lines=$(docker exec "$N" wc -l /etc/neko/browser-launch.sh | awk '{print $1}') + trap=$(docker exec "$N" grep -c on_supervisor_stop /etc/neko/browser-launch.sh || echo 0) + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=0; load=False; sw=-1 +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw}") +PY +) + echo "$N lines=$lines trap=$trap $out" +done +curl -sS -m 8 -o /dev/null -w 'dylive_neko7=%{http_code}\n' https://dylive.nomadro.com/neko/7/ || true +""" + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_restart_vps_nekos_remount.sh", "w") as f: + f.write(script) + sftp.close() + print("===== VPS =====") + _i, o, e = c.exec_command("bash /tmp/_restart_vps_nekos_remount.sh", timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def main() -> None: + run_phys() + run_vps() + + +if __name__ == "__main__": + main() diff --git a/scripts/_restore_perfect_neko.py b/scripts/_restore_perfect_neko.py new file mode 100644 index 0000000..56cc89e --- /dev/null +++ b/scripts/_restore_perfect_neko.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Restore perfect Neko per source: soft TM seed (no Cookie wipe) + edge FRP parity. + +Physical assign + ops: copy Tampermonkey + LES (prefer profile7 if has Auto Dismiss), +sync Preferences only, supervisorctl restart google-chrome — NEVER docker recreate. +VPS: keep FRP :1920x remap; soft-seed running local nekos; leave profiles intact. +""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +EXT = "dhdgffkkebhmkfjojejmpbldmpobfkfo" + +# Soft seed inside container — NEVER touches Cookies / Secure Preferences / Login Data +SEED_PY = r''' +import json, shutil, os +from pathlib import Path +EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo" +BASE=Path("/home/neko/.config/google-chrome/Default") +# chromium mount is same host dir — keep in sync +BASE2=Path("/home/neko/.config/chromium/Default") +SEED=Path("/etc/neko/tampermonkey-seed/Default") +HOST_LES=Path(os.environ.get("HOST_LES_SRC") or "") # optional override path mounted? use seed + +def load(p): + try: return json.loads(p.read_text(encoding="utf-8")) + except Exception: return {} + +def has_dismiss(p: Path) -> bool: + if not p.is_dir(): return False + for f in p.iterdir(): + if f.is_file() and f.stat().st_size: + try: + if b"YouTube Studio Auto Dismiss" in f.read_bytes(): + return True + except Exception: + pass + return False + +def seed_one(base: Path): + if not base.exists(): + base.mkdir(parents=True, exist_ok=True) + seed_ext = SEED/"Extensions"/EXT + if not seed_ext.exists(): + print("NO_SEED_EXT"); return + dst = base/"Extensions"/EXT + if dst.exists(): + shutil.rmtree(dst, ignore_errors=True) + (base/"Extensions").mkdir(parents=True, exist_ok=True) + shutil.copytree(seed_ext, dst) + mf = dst/"5.5.0_0"/"manifest.json" + if mf.exists(): + md=load(mf); md.pop("update_url", None) + mf.write_text(json.dumps(md, ensure_ascii=False, indent=3)+"\n", encoding="utf-8") + # LES: keep if already has Auto Dismiss; else copy seed or leave + les = base/"Local Extension Settings"/EXT + seed_les = SEED/"Local Extension Settings"/EXT + if has_dismiss(les): + print("les_keep_ok") + else: + if les.exists(): + shutil.rmtree(les, ignore_errors=True) + if seed_les.exists() and has_dismiss(seed_les): + (base/"Local Extension Settings").mkdir(parents=True, exist_ok=True) + shutil.copytree(seed_les, les) + for lock in (les/"LOCK",): + if lock.exists(): lock.unlink(missing_ok=True) + print("les_from_seed") + else: + print("les_seed_empty_skip") + # Preferences — TM entry only + seed_entry=((load(SEED/"Preferences").get("extensions") or {}).get("settings") or {}).get(EXT) or {} + entry=dict(seed_entry) if isinstance(seed_entry, dict) else {} + entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False}) + entry.pop("disable_reasons", None) + mf2=entry.get("manifest") + if isinstance(mf2, dict): + mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2 + pref=base/"Preferences" + d=load(pref) if pref.exists() else {} + d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry) + d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True + pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8") + print("prefs_tm_ok", base) + +for b in (BASE, BASE2): + if b.parent.exists() or b==BASE: + seed_one(b) +print("DONE_SEED") +''' + + +def ssh(host, port, user, pw): + last = None + for i in range(8): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, port, user, pw, + timeout=45, banner_timeout=120, + allow_agent=False, look_for_keys=False, + ) + return c + except Exception as ex: + last = ex + print("retry", i, ex, flush=True) + time.sleep(3) + raise SystemExit(last) + + +def run(c, cmd, t=420): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-16000:] if len(out) > 16000 else out, flush=True) + return code, out + + +def prepare_local_seed(): + # offline Preferences + strip update_url + pref = ROOT / "backend/neko/tampermonkey-seed/Default/Preferences" + d = json.loads(pref.read_text(encoding="utf-8")) + e = d["extensions"]["settings"][EXT] + e["location"] = 4 + e["from_webstore"] = False + if isinstance(e.get("manifest"), dict): + e["manifest"].pop("update_url", None) + pref.write_text(json.dumps(d, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + mf = ( + ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions" + / EXT + / "5.5.0_0" + / "manifest.json" + ) + md = json.loads(mf.read_text(encoding="utf-8")) + md.pop("update_url", None) + mf.write_text(json.dumps(md, ensure_ascii=False, indent=3) + "\n", encoding="utf-8") + # refresh provisioning hash into policies + import subprocess + + subprocess.check_call( + [sys.executable, str(ROOT / "backend/neko/render_tampermonkey_provisioning.py"), "--write"], + cwd=str(ROOT), + ) + out = subprocess.check_output( + [sys.executable, str(ROOT / "backend/neko/render_tampermonkey_provisioning.py")], + cwd=str(ROOT), + text=True, + ) + h = "" + for line in out.splitlines(): + if line.startswith("hash="): + h = line.split("=", 1)[1].strip() + if h: + pol = ROOT / "backend/neko/policies/policies.json" + data = json.loads(pol.read_text(encoding="utf-8")) + data["3rdparty"]["extensions"][EXT]["jsonImport"][0]["hash"] = h + pol.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("policies hash", h, flush=True) + + +def restore_physical(): + print("\n########## PHYSICAL RESTORE ##########", flush=True) + c = ssh("107.173.30.245", 4014, "eric", "4669805") + sftp = c.open_sftp() + uploads = { + "/tmp/browser-launch.sh.rest": ROOT / "backend/neko/browser-launch.sh", + "/tmp/policies.json.rest": ROOT / "backend/neko/policies/policies.json", + "/tmp/Preferences.seed.rest": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences", + "/tmp/manifest.json.rest": ROOT + / "backend/neko/tampermonkey-seed/Default/Extensions" + / EXT + / "5.5.0_0" + / "manifest.json", + "/tmp/youtube-studio-auto-dismiss.user.js.rest": ROOT + / "backend/neko/provisioning/youtube-studio-auto-dismiss.user.js", + "/tmp/tampermonkey-provisioning.json.rest": ROOT + / "backend/neko/provisioning/tampermonkey-provisioning.json", + "/tmp/_seed_tm_soft.py": None, # written below + } + for remote, local in uploads.items(): + if local is None: + continue + with sftp.file(remote, "wb") as f: + f.write(local.read_bytes()) + print("up", remote, flush=True) + with sftp.file("/tmp/_seed_tm_soft.py", "w") as f: + f.write(SEED_PY) + sftp.close() + + run( + c, + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set -euo pipefail +N=/opt/douyinWEB/backend/neko +# sync host assets (bind-mounted into containers) +cat /tmp/browser-launch.sh.rest > "$N/browser-launch.sh" +chmod a+rx "$N/browser-launch.sh" +cat /tmp/policies.json.rest > "$N/policies/policies.json" +chmod 644 "$N/policies/policies.json" +cat /tmp/Preferences.seed.rest > "$N/tampermonkey-seed/Default/Preferences" +chmod 644 "$N/tampermonkey-seed/Default/Preferences" +MF="/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" +cat /tmp/manifest.json.rest > "$MF" +chmod 644 "$MF" +install -m 644 /tmp/youtube-studio-auto-dismiss.user.js.rest "$N/provisioning/youtube-studio-auto-dismiss.user.js" +install -m 644 /tmp/tampermonkey-provisioning.json.rest "$N/provisioning/tampermonkey-provisioning.json" + +P=/opt/douyinWEB/backend/data/neko/profiles +OP=/opt/douyinWEB/backend/data/ops_neko/profiles +SEED_LES="$N/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" +GOOD7="$P/7/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" + +NAMES=$(docker ps --format "{{.Names}}" | grep -E "^douyinweb-(neko|ops-neko)-[0-9]+$" | sort) +echo "running: $NAMES" +# Stop Chrome first so host profile copies are safe +for name in $NAMES; do + docker exec "$name" supervisorctl stop google-chrome || true +done +sleep 2 + +if grep -R -a -q "YouTube Studio Auto Dismiss" "$GOOD7" 2>/dev/null; then + if ! grep -R -a -q "YouTube Studio Auto Dismiss" "$SEED_LES" 2>/dev/null; then + echo "clone LES from profile7 -> seed" + rm -rf "$SEED_LES" + mkdir -p "$(dirname "$SEED_LES")" + cp -a "$GOOD7" "$SEED_LES" + rm -f "$SEED_LES/LOCK" 2>/dev/null || true + fi +fi + +soft_host_les() { + local root="$1" id="$2" + local dst="$root/$id/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo" + if grep -R -a -q "YouTube Studio Auto Dismiss" "$dst" 2>/dev/null; then + echo "${root##*/}/$id les ok"; return 0 + fi + if grep -R -a -q "YouTube Studio Auto Dismiss" "$SEED_LES" 2>/dev/null; then + mkdir -p "$(dirname "$dst")" + rm -rf "$dst" + cp -a "$SEED_LES" "$dst" + rm -f "$dst/LOCK" 2>/dev/null || true + chown -R eric:eric "$root/$id/Default/Local Extension Settings" 2>/dev/null || true + echo "${root##*/}/$id les seeded" + fi +} +for id in 1 2 3 4 5 6 7 8; do soft_host_les "$P" "$id"; done +for id in 1 2; do soft_host_les "$OP" "$id"; done + +for name in $NAMES; do + echo "===== SEED $name =====" + docker cp /tmp/_seed_tm_soft.py "$name":/tmp/_seed_tm_soft.py + docker exec "$name" python3 /tmp/_seed_tm_soft.py || echo SEED_FAIL + docker exec "$name" supervisorctl start google-chrome || docker exec "$name" supervisorctl restart google-chrome || true +done +sleep 15 +for name in $NAMES; do + echo "===== VERIFY $name =====" + docker exec "$name" python3 - < "$N/browser-launch.sh" +chmod a+rx "$N/browser-launch.sh" +cat /tmp/policies.json.rest > "$N/policies/policies.json" +cat /tmp/Preferences.seed.rest > "$N/tampermonkey-seed/Default/Preferences" +MF="$N/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json" +cat /tmp/manifest.json.rest > "$MF" +install -m 0644 /tmp/host_profile.py /opt/douyinWEB/backend/app/host_profile.py +install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py + +# Ensure FRP still uses 1920x (do not steal dylive :920x) +grep -q '19200:127.0.0.1:9200' /etc/systemd/system/dy-frp-http-aux.service && echo frp_1920x_ok || echo frp_NEED_FIX +grep -A1 'handle_path /neko/1/\*' /etc/caddy/sites/dy.nomadro.com.caddy | head -3 +systemctl is-active dy-frp-http-aux caddy douyinweb-api + +# Soft-seed only RUNNING local dylive nekos (no recreate) +NAMES=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort) +echo "vps_running: $NAMES" +for name in $NAMES; do + echo "===== SEED $name =====" + docker exec "$name" supervisorctl stop google-chrome || true + sleep 1 + docker cp /tmp/_seed_tm_soft.py "$name":/tmp/_seed_tm_soft.py + docker exec "$name" python3 /tmp/_seed_tm_soft.py || echo SEED_FAIL + docker exec "$name" supervisorctl start google-chrome || true +done +# restart api for host_profile code +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api +curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 120; echo +echo VPS_OK +""", + 300, + ) + c.close() + + +def verify_public(): + print("\n########## PUBLIC VERIFY ##########", flush=True) + with httpx.Client(follow_redirects=False, timeout=25) as cl: + for u in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/7/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + "https://dy.nomadro.cn/ops-neko/2/", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(u) + print(f"{r.status_code} {u}", flush=True) + except Exception as ex: + print(f"ERR {u} {ex}", flush=True) + + +def main(): + prepare_local_seed() + restore_physical() + restore_vps_edge_and_local() + verify_public() + print("\nALL_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_restore_relay_after_endtest.py b/scripts/_restore_relay_after_endtest.py new file mode 100644 index 0000000..67866ac --- /dev/null +++ b/scripts/_restore_relay_after_endtest.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +cmd = r''' +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +from app import db +# restore auto relay for operator testing; leave timeslot_test as-is +db.update_settings_map({"youtube_relay_enabled": True}) +cfg=db.get_settings_map() +print("relay", cfg.get("youtube_relay_enabled"), "test", cfg.get("youtube_relay_timeslot_test"), "gid", cfg.get("youtube_relay_timeslot_test_group_id")) +# final studio scrape +import subprocess, json +raw=subprocess.check_output( + ["docker","exec","-i","douyinweb-neko-7","python3","-"], + input=open("/opt/douyinWEB/backend/neko/cdp_studio_scrape.py","rb").read(), + timeout=30, +) +line=raw.decode().strip().splitlines()[-1] +d=json.loads(line) +print("final_studio", {k:d.get(k) for k in ("live_status","on_air","health","url")}) +PY +''' +_, o, e = c.exec_command(cmd, timeout=60) +print((o.read()+e.read()).decode("utf-8","replace")) +c.close() diff --git a/scripts/_restore_shellcrash_yaml.py b/scripts/_restore_shellcrash_yaml.py new file mode 100644 index 0000000..f89f269 --- /dev/null +++ b/scripts/_restore_shellcrash_yaml.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Restore ShellCrash config from backup after unauthorized edit. Live flush.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = r''' +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +if [ -f /tmp/ShellCrash/config.yaml.bak.hysteria_ports ]; then + cp -a /tmp/ShellCrash/config.yaml.bak.hysteria_ports /tmp/ShellCrash/config.yaml + echo restored_from_bak +else + echo NO_BACKUP +fi +grep -A12 "name: 1d2da142-singbox_hysteria5" /tmp/ShellCrash/config.yaml | head -14 +systemctl restart shellcrash.service +sleep 4 +systemctl is-active shellcrash +' +''' +_i, o, e = c.exec_command(cmd, timeout=60) +while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) +sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) +sys.stdout.flush() +print("->", o.channel.recv_exit_status(), flush=True) +c.close() +print("DONE", flush=True) diff --git a/scripts/_restore_wg_probe_frp.py b/scripts/_restore_wg_probe_frp.py new file mode 100644 index 0000000..561a4e2 --- /dev/null +++ b/scripts/_restore_wg_probe_frp.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Restore wg-dy to :51820, then probe FRP HTTP path for dy.nomadro.com. +Physical = 107.173.30.245:4014 eric/4669805. No Neko. Live flush. +""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +GUEST = ("107.173.30.245", 4014, "eric", "4669805") + + +def connect(spec): + host, port, user, pw = spec + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + pw, + timeout=25, + banner_timeout=40, + allow_agent=False, + look_for_keys=False, + ) + print(f"connected {user}@{host}:{port}", flush=True) + return c + except Exception as ex: + print(f"retry {port} {i}: {ex}", flush=True) + time.sleep(2) + raise RuntimeError(f"ssh fail :{port}") + + +def run(c, cmd, t=90): + print(f"$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) + sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) + sys.stdout.flush() + print("->", o.channel.recv_exit_status(), flush=True) + + +print("## 1 restore VPS wg-dy ListenPort 51820", flush=True) +v = connect(VPS) +run( + v, + "cp -a /etc/wireguard/wg-dy.conf.bak.pre443 /etc/wireguard/wg-dy.conf 2>/dev/null || " + "sed -i 's/^ListenPort = .*/ListenPort = 51820/' /etc/wireguard/wg-dy.conf; " + "grep -E 'ListenPort|Address|AllowedIPs|PublicKey' /etc/wireguard/wg-dy.conf; " + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; " + "wg show wg-dy; " + "ss -ulnp | grep 51820 || true", +) +v.close() + +print("## 2 restore guest Endpoint :51820", flush=True) +g = connect(GUEST) +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "cp -a /etc/wireguard/wg-dy.conf.bak.pre443 /etc/wireguard/wg-dy.conf 2>/dev/null || true; " + "sed -i \"s/^Endpoint = .*/Endpoint = 107.173.30.245:51820/\" /etc/wireguard/wg-dy.conf; " + "grep -E \"Endpoint|Address|Keepalive|AllowedIPs\" /etc/wireguard/wg-dy.conf; " + "wg-quick down wg-dy 2>/dev/null || true; " + "wg-quick up wg-dy; sleep 3; " + "wg show wg-dy; " + "systemctl is-active douyinweb-api douyinweb-web; " + "curl -sS -m 6 http://127.0.0.1:8014/api/health | head -c 120; echo" + "'", + t=60, +) +g.close() + +print("## 3 FRP inventory on VPS (ports that might reach guest HTTP)", flush=True) +v = connect(VPS) +run( + v, + "systemctl is-active frpp; " + "ss -lntp | grep -E 'frp|4014|7000|8999|8014|4015|18014|14015|8080|8443' || true; " + "ls /opt /etc | grep -i frp || true; " + "find /opt /etc /root -maxdepth 3 -iname '*frp*' -type f 2>/dev/null | head -30; " + "curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 80; echo; " + "curl -sS -m 5 -o /dev/null -w dylive_local=%{http_code}\\\\n http://127.0.0.1:4015/", + t=40, +) +v.close() + +print("## 4 guest frpc status / local listen", flush=True) +g = connect(GUEST) +run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "ss -lntp | grep -E \":(8014|4015)\\b\"; " + "systemctl list-units --type=service --state=running | grep -iE \"frp|nps|gost\" || true; " + "ps aux | grep -iE \"[f]rpc|[f]rps\" | head -10; " + "ls /etc/frp /opt/frp /home/eric/frp 2>/dev/null; " + "find /etc /opt /home/eric -maxdepth 3 -name \"frpc*.toml\" -o -name \"frpc*.ini\" 2>/dev/null | head -20" + "'", + t=40, +) +g.close() + +print("## 5 tunnel + public", flush=True) +time.sleep(2) +v = connect(VPS) +run( + v, + "wg show wg-dy | head -20; " + "ping -c 3 -W 2 10.8.0.2 | tail -5; " + "curl -sS -m 8 -o /dev/null -w via_wg=%{http_code}\\\\n http://10.8.0.2:8014/api/health", + t=30, +) +v.close() + +with httpx.Client(follow_redirects=False, timeout=15) as cl: + for u in [ + "https://dylive.nomadro.com/api/health", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/", + "https://dy.nomadro.cn/api/health", + ]: + try: + print(f"{u} -> {cl.get(u).status_code}", flush=True) + except Exception as ex: + print(f"{u} ERR {ex}", flush=True) + +print("DONE", flush=True) diff --git a/scripts/_resume_merge_ops_to_dy.py b/scripts/_resume_merge_ops_to_dy.py new file mode 100644 index 0000000..42a176a --- /dev/null +++ b/scripts/_resume_merge_ops_to_dy.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Resume merge of /tmp/dylive_ops_export.db into dy.nomadro.live.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +TABLES = [ + "rooms", + "blacklist", + "channel_groups", + "shorts_channels", + "yt_long_channels", + "yt_assign_groups", + "yt_assign_pool_urls", + "yt_assign_featured_urls", + "yt_assign_slot_urls", +] + + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + +cmd = r""" +set -euo pipefail +cd /opt/douyinWEB/backend +test -f /tmp/dylive_ops_export.db + +./.venv/bin/python - <<'PY' +import json, sqlite3 +from pathlib import Path +from app import db + +SRC = Path("/tmp/dylive_ops_export.db") +DST = Path("/opt/douyinWEB/backend/data/monitor.db") +TABLES = __TABLES__ + +# touch schema by listing +_ = db.list_rooms() +_ = db.list_shorts_channels() +from app import yt_assign_db +_ = yt_assign_db.list_groups(include_urls=False) + +src = sqlite3.connect(str(SRC)) +dst = sqlite3.connect(str(DST)) +src.row_factory = sqlite3.Row + +def cols(con, table): + return [r[1] for r in con.execute(f"PRAGMA table_info([{table}])").fetchall()] + +def exists(con, table): + return bool(con.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,) + ).fetchone()) + +report = {} +for t in TABLES: + if not exists(src, t): + report[t] = {"skipped": "missing_src"} + continue + if not exists(dst, t): + schema = src.execute( + "SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,) + ).fetchone() + if schema and schema[0]: + dst.execute(schema[0]); dst.commit() + else: + report[t] = {"skipped": "no_schema"} + continue + sc, dc = cols(src, t), cols(dst, t) + common = [c for c in sc if c in dc] + rows = src.execute(f"SELECT * FROM [{t}]").fetchall() + before = dst.execute(f"SELECT COUNT(*) FROM [{t}]").fetchone()[0] + dst.execute(f"DELETE FROM [{t}]") + inserted = 0 + for r in rows: + d = dict(r) + if t == "yt_assign_groups" and "neko_instance_id" in d: + try: + nid = int(d.get("neko_instance_id") or 0) + except Exception: + nid = 0 + if nid > 8: + d["neko_instance_id"] = ((nid - 1) % 8) + 1 + vals = [d.get(c) for c in common] + placeholders = ",".join(["?"] * len(common)) + colnames = ",".join(f"[{c}]" for c in common) + dst.execute( + f"INSERT OR REPLACE INTO [{t}] ({colnames}) VALUES ({placeholders})", + vals, + ) + inserted += 1 + dst.commit() + after = dst.execute(f"SELECT COUNT(*) FROM [{t}]").fetchone()[0] + report[t] = {"src": len(rows), "before": before, "after": after, "inserted": inserted} + +dst.close(); src.close() +print(json.dumps(report, ensure_ascii=False, indent=2)) + +rooms = db.list_rooms() +print("rooms_total", rooms.get("total") if isinstance(rooms, dict) else len(rooms)) +chs = db.list_shorts_channels() +print("shorts_channels", len(chs), "with_rt", sum(1 for x in chs if str(x.get("refresh_token") or "").strip())) +groups = yt_assign_db.list_groups(include_urls=False) +print("assign_groups", len(groups)) +print("neko_ids", sorted({int(g.get("neko_instance_id") or 0) for g in groups})) +PY + +systemctl restart douyinweb-api douyinweb-web +sleep 5 +systemctl is-active douyinweb-api douyinweb-web + +# firewall +set +e +if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -qi active; then + ufw allow 52000:52499/udp || true + ufw allow 52000:52499/tcp || true + ufw allow 52300:52320/udp || true + ufw allow 52300:52320/tcp || true +else + iptables -C INPUT -p udp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52000:52499 -j ACCEPT + iptables -C INPUT -p tcp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport 52000:52499 -j ACCEPT + iptables -C INPUT -p udp --dport 52300:52320 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52300:52320 -j ACCEPT + echo iptables_ok +fi + +curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/l.json -w 'login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \ + -H 'Content-Type: application/json' -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/l.json; echo +curl -sS -b /tmp/dyj 'https://dy.nomadro.live/api/rooms?limit=3' | ./.venv/bin/python -c 'import sys,json;d=json.load(sys.stdin);print("rooms",d.get("total"), "n",len(d.get("rooms") or []))' +curl -sS -b /tmp/dyj https://dy.nomadro.live/api/shorts/channels | ./.venv/bin/python -c 'import sys,json;d=json.load(sys.stdin);rows=d if isinstance(d,list) else d.get("channels") or d.get("items") or [];print("channels",len(rows));print([r.get("name") for r in rows[:6]])' +curl -sS -b /tmp/dyj https://dy.nomadro.live/api/youtube/assign/groups | ./.venv/bin/python -c 'import sys,json;d=json.load(sys.stdin);rows=d if isinstance(d,list) else d.get("groups") or [];print("assign",len(rows));print([(r.get("name"), r.get("neko_instance_id")) for r in rows[:8]])' +""".replace("__TABLES__", repr(TABLES)) + +_i, o, e = c.exec_command(cmd, timeout=300) +print((o.read() + e.read()).decode("utf-8", "replace")) +print("exit", o.channel.recv_exit_status()) +c.close() +print("DONE", time.strftime("%H:%M:%S")) diff --git a/scripts/_retest_end_confirm_dylive.py b/scripts/_retest_end_confirm_dylive.py new file mode 100644 index 0000000..ecec143 --- /dev/null +++ b/scripts/_retest_end_confirm_dylive.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +"""Deploy fixed confirm + retest graceful End on neko-7.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +sftp.put(str(ROOT / "backend/neko/cdp_end_stream.py"), "/tmp/cdp_end_stream.py") +runner = r'''#!/bin/bash +set -euo pipefail +install -m 0644 /tmp/cdp_end_stream.py /opt/douyinWEB/backend/neko/cdp_end_stream.py +NAME=douyinweb-neko-7 +NEKO_ID=7 +CHANNEL_PK=82102486-f5d7-434c-b508-4c6a10c5f325 + +cd /opt/douyinWEB/backend +# Pause auto-relay so ffmpeg does not respawn mid-test +./.venv/bin/python - <<'PY' +from app import db +cfg=db.get_settings_map() +open("/tmp/relay_prev.json","w").write(repr({ + "youtube_relay_enabled": bool(cfg.get("youtube_relay_enabled")), + "youtube_relay_timeslot_test": bool(cfg.get("youtube_relay_timeslot_test")), +})) +db.update_settings_map({"youtube_relay_enabled": False}) +print("relay_paused") +PY + +echo '=== BEFORE ===' +docker exec -i "$NAME" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tee /tmp/before.json | python3 -c 'import sys,json;d=json.load(sys.stdin);print({k:d.get(k) for k in ("live_status","on_air","health")})' + +echo '=== kill ffmpeg PIDs ===' +python3 - <<'PY' +import os, signal, subprocess, time +for _ in range(3): + out=subprocess.check_output(["ps","-eo","pid,args"], text=True, errors="replace") + n=0 + for line in out.splitlines(): + if "ffmpeg" in line and "youtube" in line.lower() and "python" not in line: + pid=int(line.split(None,1)[0]) + print("kill", pid) + try: os.kill(pid, signal.SIGTERM); n+=1 + except ProcessLookupError: pass + print("killed_batch", n) + time.sleep(1) +PY + +sleep 10 +echo '=== MID ===' +docker exec -i "$NAME" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tee /tmp/mid.json | python3 -c 'import sys,json;d=json.load(sys.stdin);print({k:d.get(k) for k in ("live_status","on_air","health")})' + +echo '=== end_live_session ===' +./.venv/bin/python - < 22000 else out, flush=True) +c.close() +raise SystemExit(code) diff --git a/scripts/_revive_dylive_neko12.py b/scripts/_revive_dylive_neko12.py new file mode 100644 index 0000000..0ac9e32 --- /dev/null +++ b/scripts/_revive_dylive_neko12.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Recover dylive neko-12 without recreate; check why it stopped.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e) + time.sleep(2) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== before ===' +docker ps -a --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +docker inspect douyinweb-neko-12 --format 'OOM={{.State.OOMKilled}} Exit={{.State.ExitCode}} Error={{.State.Error}} Finished={{.State.FinishedAt}} Status={{.State.Status}}' +dmesg -T 2>/dev/null | tail -30 | grep -iE 'oom|kill|neko|chrome' || true +free -m | head -2 + +echo '=== start (no recreate) ===' +docker start douyinweb-neko-12 +sleep 15 +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +docker exec douyinweb-neko-12 sh -c ' +supervisorctl status +grep -n js-flags /etc/neko/browser-launch.sh | head -1 +rm -f /home/neko/.config/google-chrome/Singleton* 2>/dev/null +supervisorctl start google-chrome 2>/dev/null || supervisorctl restart google-chrome +sleep 10 +supervisorctl status google-chrome +curl -sS -m 3 http://127.0.0.1:9222/json/version | head -c 160; echo +python3 - <<"PY" +import json,urllib.request +try: + tabs=json.load(urllib.request.urlopen("http://127.0.0.1:9222/json",timeout=5)) + print("tabs",len(tabs)) + for t in tabs: + if "studio" in (t.get("url") or ""): + print("studio", (t.get("url") or "")[:100]) +except Exception as e: + print("err",e) +PY +' +free -m | head -2 +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_revive_fast.py b/scripts/_revive_fast.py new file mode 100644 index 0000000..f33595d --- /dev/null +++ b/scripts/_revive_fast.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Fast emergency revive: dylive local + wg-dy bounce. No long probes.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(port, user, pw, tries=8): + last = None + for i in range(tries): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + port, + user, + pw, + timeout=30, + banner_timeout=90, + allow_agent=False, + look_for_keys=False, + ) + print(f"ok :{port} try={i}", flush=True) + return c + except Exception as ex: + last = ex + print(f"retry :{port} {i} {ex}", flush=True) + time.sleep(3) + raise SystemExit(f"fail :{port} {last}") + + +def run(c, cmd, t=60): + print(f"$ {cmd[:180]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-4000:] if out else f"(empty code={code})", flush=True) + return code + + +# 1) VPS: kill hung restarts lightly, start essentials only +v = ssh(22, "root", "Xiao4669805") +run( + v, + "uptime; free -h | head -2; " + "systemctl start caddy nginx frpp docker; " + "systemctl start douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "systemctl is-active caddy douyinweb-api douyinweb-web", + 45, +) +run(v, "wg-quick down wg-dy >/dev/null 2>&1; wg-quick up wg-dy; sleep 1; wg show wg-dy | head -12", 40) +run(v, "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 180; echo", 20) +v.close() + +# 2) Physical guest via FRP +try: + g = ssh(4014, "eric", "4669805") + run( + g, + "echo 4669805 | sudo -S -p '' bash -lc '" + "wg-quick down wg-dy >/dev/null 2>&1; wg-quick up wg-dy; " + "systemctl start douyinweb-api douyinweb-web; " + "sleep 2; wg show wg-dy | head -10; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 120; echo; " + "systemctl is-active douyinweb-api douyinweb-web" + "'", + 70, + ) + g.close() +except Exception as ex: + print("guest err", ex, flush=True) + +# 3) tunnel check from VPS +v = ssh(22, "root", "Xiao4669805") +run(v, "ping -c 2 -W 2 10.8.0.2 | tail -3; curl -sS -m 8 -o /dev/null -w 'wg_api=%{http_code}\\n' http://10.8.0.2:8014/api/health; curl -sS -m 8 -o /dev/null -w 'local=%{http_code}\\n' http://127.0.0.1:8014/api/health", 30) +v.close() +print("DONE_FAST", flush=True) diff --git a/scripts/_revive_neko_and_finish_key_ui.py b/scripts/_revive_neko_and_finish_key_ui.py new file mode 100644 index 0000000..337ccdc --- /dev/null +++ b/scripts/_revive_neko_and_finish_key_ui.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Emergency: docker start stopped nekos on dy (no recreate). Then finish dylive deploy carefully.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +FILES = [ + "backend/app/yt_assign_db.py", + "backend/app/yt_stream_key_db.py", + "backend/app/youtube_relay_status.py", + "backend/app/main.py", + "frontend/src/lib/ytRelayStatus.ts", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/app/youtube-relay-log/page.tsx", +] + + +def connect(host: str): + last = None + for i in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + 22, + "root", + PASS, + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=240, + ) + return c + except Exception as e: + last = e + print("retry", i, e, flush=True) + time.sleep(3 + i) + raise SystemExit(last) + + +def run(c, cmd, t=600): + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + code = o.channel.recv_exit_status() + print(out[-8000:] if len(out) > 8000 else out, flush=True) + return code, out + + +print("===== revive dy neko 2/3 =====", flush=True) +dy = connect("108.174.50.68") +run( + dy, + r""" +set +e +echo before: +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +# ONLY start — never rm/recreate +docker start douyinweb-neko-2 douyinweb-neko-3 +sleep 8 +echo after: +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +free -h | head -2 +# confirm profiles mounts still there +docker inspect douyinweb-neko-2 --format '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{println}}{{end}}' | grep profiles || true +""", +) +dy.close() + +print("===== dylive: API only first, build with swap pressure care =====", flush=True) +dl = connect("107.173.30.245") +_, before = run(dl, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; free -h | head -2") +sftp = dl.open_sftp() +for rel in FILES: + local = ROOT / rel + remote = f"/opt/douyinWEB/{rel}" + run(dl, f"mkdir -p {'/'.join(remote.split('/')[:-1])}") + print("put", rel, flush=True) + sftp.put(str(local), remote) +sftp.close() + +# API restart only — skip npm build on low-mem host; rsync .next from dy instead +run( + dl, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python -c 'from app import yt_assign_db; gs=yt_assign_db.list_groups(include_urls=False, include_secret=True); print(len(gs), sum(1 for g in gs if g.get("stream_key")))' +systemctl restart douyinweb-api +sleep 4 +systemctl is-active douyinweb-api +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +""", +) +dl.close() + +# Copy built frontend artifacts from dy -> dylive to avoid OOM build on 3.8G +print("===== copy .next from dy to dylive =====", flush=True) +dy = connect("108.174.50.68") +# tar .next + relevant static on dy, stream via sftp is heavy; use scp-like paramiko +run( + dy, + r""" +set -euo pipefail +cd /opt/douyinWEB/frontend +tar -czf /tmp/dy-next-keys.tgz .next/static .next/server .next/BUILD_ID 2>/dev/null || tar -czf /tmp/dy-next-keys.tgz .next +ls -lh /tmp/dy-next-keys.tgz +""", +) +# download to local then upload to dylive +sftp = dy.open_sftp() +local_tgz = ROOT / "scripts" / "_dy_next_keys.tgz" +sftp.get("/tmp/dy-next-keys.tgz", str(local_tgz)) +sftp.close() +dy.close() +print("downloaded", local_tgz.stat().st_size, flush=True) + +dl = connect("107.173.30.245") +_, before2 = run(dl, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") +sftp = dl.open_sftp() +sftp.put(str(local_tgz), "/tmp/dy-next-keys.tgz") +# also ensure source files for keys page exist +for rel in [ + "frontend/src/app/youtube/keys/page.tsx", + "frontend/src/components/YtAssignPanel.tsx", + "frontend/src/components/YtRelayProStatusPanel.tsx", +]: + sftp.put(str(ROOT / rel), f"/opt/douyinWEB/{rel}") +sftp.close() +run( + dl, + r""" +set -euo pipefail +cd /opt/douyinWEB/frontend +# backup then extract built assets only +mkdir -p .next +tar -xzf /tmp/dy-next-keys.tgz -C /opt/douyinWEB/frontend +systemctl restart douyinweb-web +sleep 3 +systemctl is-active douyinweb-web +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort +curl -sk -o /dev/null -w 'keys:%{http_code}\n' https://dylive.nomadro.com/youtube/keys +curl -sk -o /dev/null -w 'yt:%{http_code}\n' https://dylive.nomadro.com/youtube +""", +) +_, after2 = run(dl, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") +before_up = {ln.split()[0] for ln in before2.splitlines() if " Up " in ln and "neko" in ln} +after_up = {ln.split()[0] for ln in after2.splitlines() if " Up " in ln and "neko" in ln} +lost = before_up - after_up +if lost: + print("CRITICAL dylive neko lost", lost) + # try start only + run(dl, "docker start " + " ".join(lost) + "; sleep 5; docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort") +dl.close() + +# final dy check +dy = connect("108.174.50.68") +run(dy, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; curl -sk -o /dev/null -w 'keys:%{http_code}\\n' https://dy.nomadro.live/youtube/keys") +dy.close() +print("DONE") diff --git a/scripts/_route_nomadro_apex.py b/scripts/_route_nomadro_apex.py new file mode 100644 index 0000000..ff81cf0 --- /dev/null +++ b/scripts/_route_nomadro_apex.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Find how apex nomadro.com is proxied; start Next only (no WP).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r"""#!/bin/bash +set -e +echo '=== proxy config for apex ===' +grep -RIn --include='*' -E 'server_name\s+.*nomadro\.com|nomadro\.com|4403|4003|8088' /etc/nginx/sites-enabled /etc/nginx/conf.d /etc/caddy 2>/dev/null | head -80 +ls -la /etc/nginx/sites-enabled/ 2>/dev/null +echo '=== router source ===' +head -80 /var/www/nomadro-router/server.mjs 2>/dev/null || true +echo '=== current status ===' +systemctl is-active nomadro.service nomadro-router.service 2>/dev/null || true +ss -lntp | grep -E ':4003|:4403|:8088' || true +curl -sS -m 8 -o /dev/null -w 'public_nomadro=%{http_code}\n' -L https://nomadro.com/ || true +curl -sS -m 8 -o /dev/null -w 'public_www=%{http_code}\n' -L https://www.nomadro.com/ || true +""" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_route_nomadro.sh", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_route_nomadro.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_run_fix_nomadro_caddy.py b/scripts/_run_fix_nomadro_caddy.py new file mode 100644 index 0000000..fb3a202 --- /dev/null +++ b/scripts/_run_fix_nomadro_caddy.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parent / "_fix_nomadro_caddy_next.sh" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_nomadro_caddy_next.sh", "wb") as f: + f.write(LOCAL.read_bytes()) + sftp.close() + _, o, e = c.exec_command( + "sed -i 's/\\r$//' /tmp/_fix_nomadro_caddy_next.sh && bash /tmp/_fix_nomadro_caddy_next.sh", + timeout=120, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_run_fix_opsneko_tm_ext.py b/scripts/_run_fix_opsneko_tm_ext.py new file mode 100644 index 0000000..8e1b53c --- /dev/null +++ b/scripts/_run_fix_opsneko_tm_ext.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "_remote_fix_opsneko_tm_ext.sh" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_fix_opsneko_tm_ext.sh", "wb") as f: + data = SCRIPT.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + f.write(data) + sftp.close() + cmd = "echo 4669805 | sudo -S -p '' bash /tmp/_fix_opsneko_tm_ext.sh" + _i, o, e = c.exec_command(cmd, timeout=240) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_run_fix_opsneko_tm_ext2.py b/scripts/_run_fix_opsneko_tm_ext2.py new file mode 100644 index 0000000..50ab386 --- /dev/null +++ b/scripts/_run_fix_opsneko_tm_ext2.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +INSIDE = ROOT / "scripts" / "_opsneko_tm_ext_inside.py" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_opsneko_tm_ext_inside.py", "wb") as f: + f.write(INSIDE.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")) + sftp.close() + + remote = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + docker cp /tmp/_opsneko_tm_ext_inside.py $name:/tmp/_opsneko_tm_ext_inside.py + echo --- BEFORE --- + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py diag + docker exec $name supervisorctl stop google-chrome || true + sleep 2 + echo --- REPAIR --- + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py repair + docker exec $name bash -lc "chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences; [ -f /home/neko/.config/google-chrome/Default/Secure\ Preferences ] && chown neko:neko /home/neko/.config/google-chrome/Default/Secure\ Preferences; true" + docker exec $name supervisorctl start google-chrome +done +sleep 12 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== VERIFY $name =====" + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py diag + docker exec $name supervisorctl status google-chrome +done +' +""" + _i, o, e = c.exec_command(remote, timeout=240) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_run_fix_opsneko_tm_ext3.py b/scripts/_run_fix_opsneko_tm_ext3.py new file mode 100644 index 0000000..f18035c --- /dev/null +++ b/scripts/_run_fix_opsneko_tm_ext3.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import base64 +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +INSIDE = ROOT / "scripts" / "_opsneko_tm_ext_inside.py" +B64 = base64.b64encode(INSIDE.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")).decode("ascii") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + + # Upload to host /tmp via sftp, then pipe into each container with docker exec + sftp = c.open_sftp() + with sftp.file("/tmp/_opsneko_tm_ext_inside.py", "w") as f: + f.write(INSIDE.read_text(encoding="utf-8").replace("\r\n", "\n").replace("\r", "\n")) + sftp.close() + + remote = f""" +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +B64="{B64}" +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== $name =====" + # write script into container /tmp via base64 (avoid docker cp RO quirks) + printf %s "$B64" | docker exec -i $name bash -lc "base64 -d > /tmp/_opsneko_tm_ext_inside.py" + echo --- BEFORE --- + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py diag || true + docker exec $name supervisorctl stop google-chrome || true + sleep 2 + echo --- REPAIR --- + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py repair + docker exec $name bash -lc "chown -R neko:neko /home/neko/.config/google-chrome/Default/Extensions /home/neko/.config/google-chrome/Default/Preferences; [ -f /home/neko/.config/google-chrome/Default/Secure\\ Preferences ] && chown neko:neko /home/neko/.config/google-chrome/Default/Secure\\ Preferences; true" + docker exec $name supervisorctl start google-chrome +done +sleep 15 +for i in 1 2; do + name=douyinweb-ops-neko-$i + echo "===== VERIFY $name =====" + docker exec $name python3 /tmp/_opsneko_tm_ext_inside.py diag + docker exec $name supervisorctl status google-chrome +done +' +""" + _i, o, e = c.exec_command(remote, timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_run_start_nomadro_live.py b/scripts/_run_start_nomadro_live.py new file mode 100644 index 0000000..9a53c76 --- /dev/null +++ b/scripts/_run_start_nomadro_live.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +LOCAL = Path(__file__).resolve().parent / "_start_nomadro_live_next.sh" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_start_nomadro_live_next.sh", "wb") as f: + f.write(LOCAL.read_bytes()) + sftp.close() + _, o, e = c.exec_command( + "sed -i 's/\\r$//' /tmp/_start_nomadro_live_next.sh && bash /tmp/_start_nomadro_live_next.sh", + timeout=120, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_scan_assign_neko_chrome.py b/scripts/_scan_assign_neko_chrome.py new file mode 100644 index 0000000..543ce51 --- /dev/null +++ b/scripts/_scan_assign_neko_chrome.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +for i in 1 2 3 4 5 6 7 8; do + N=douyinweb-neko-$i + docker inspect "$N" >/dev/null 2>&1 || { echo "$N MISSING"; continue; } + out=$(docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +mains=[] +load=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains.append(pid) + if b"load-extension" in raw and b"dhdgff" in raw: + load=True +sw=0 +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=2).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception as e: + sw=-1 +print(f"mains={len(mains)} load_ext={load} tm_sw={sw}") +PY +) + echo "neko-$i $out" +done +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_scan_neko_chrome.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_scan_neko_chrome.sh", + timeout=120, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_scan_phys_neko_tm_now.py b/scripts/_scan_phys_neko_tm_now.py new file mode 100644 index 0000000..1213a90 --- /dev/null +++ b/scripts/_scan_phys_neko_tm_now.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Scan physical assign + ops-neko for dual chrome / TM health.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +probe() { + local N="$1" + docker inspect "$N" >/dev/null 2>&1 || { echo "$N MISSING"; return; } + docker exec -i "$N" python3 - <<'PY' +import os, json, urllib.request +from pathlib import Path +name=os.environ.get("HOSTNAME","?") +mains=[]; load=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains.append(pid) + if b"load-extension" in raw and b"dhdgff" in raw: load=True +sw=-1; tabs_n=0 +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=3).read()) + tabs_n=len(tabs) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception as e: + sw=-1 +les=Path("/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log") +ad=False +if les.exists(): + ad=b"YouTube Studio Auto Dismiss" in les.read_bytes() +trap=False +try: + trap=b"on_supervisor_stop" in open("/etc/neko/browser-launch.sh","rb").read() +except Exception: + pass +print(f"mains={len(mains)} load_ext={load} tm_sw={sw} tabs={tabs_n} auto_dismiss={ad} stop_trap={trap}") +PY +} + +echo "=== assign ===" +for i in 1 2 3 4 5 6 7 8; do + echo -n "neko-$i " + probe douyinweb-neko-$i +done +echo "=== ops ===" +for i in 1 2; do + echo -n "ops-neko-$i " + # ops container names may vary + for cand in douyinweb-ops-neko-$i ops-neko-$i; do + if docker inspect "$cand" >/dev/null 2>&1; then + echo -n "($cand) " + probe "$cand" + break + fi + done +done +echo "=== browser-launch host ===" +grep -n on_supervisor_stop /opt/douyinWEB/backend/neko/browser-launch.sh | head +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_scan_phys_neko_tm.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash /tmp/_scan_phys_neko_tm.sh", + timeout=180, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_scan_vps_neko_tm.py b/scripts/_scan_vps_neko_tm.py new file mode 100644 index 0000000..2627450 --- /dev/null +++ b/scripts/_scan_vps_neko_tm.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Scan VPS assign Nekos + sync browser-launch stop trap if needed.""" +from __future__ import annotations + +import hashlib +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend/neko/browser-launch.sh" + +SCAN = r"""#!/bin/bash +set +e +echo "=== vps browser-launch trap ===" +grep -n on_supervisor_stop /opt/douyinWEB/backend/neko/browser-launch.sh 2>/dev/null | head || echo NO_TRAP +echo "=== assign containers ===" +docker ps --format '{{.Names}}' | grep -E 'neko|douyin' | sort +for N in $(docker ps --format '{{.Names}}' | grep -E 'douyinweb-neko-[0-9]+$' | sort); do + out=$(docker exec -i "$N" python3 - <<'PY' 2>/dev/null +import os, json, urllib.request +mains=0; load=False; sw=-1 +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: raw=open(f"/proc/{pid}/cmdline","rb").read() + except: continue + if not raw: continue + if b"google-chrome" in raw and b"--type=" not in raw and b"crashpad" not in raw and b"browser-launch" not in raw: + mains += 1 + if b"load-extension" in raw and b"dhdgff" in raw: load=True +try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=2).read()) + sw=sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")) +except Exception: + sw=-1 +print(f"mains={mains} load_ext={load} tm_sw={sw}") +PY +) + echo "$N $out" +done +""" + + +def main() -> None: + data = LOCAL.read_bytes() + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=30, + allow_agent=False, + look_for_keys=False, + banner_timeout=60, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/_scan_vps_neko.sh", "w") as f: + f.write(SCAN) + with sftp.file("/tmp/browser-launch.sh.stoptrap", "w") as f: + f.write(data) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_scan_vps_neko.sh", timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + # sync trap if missing + _i, o, e = c.exec_command( + "grep -q on_supervisor_stop /opt/douyinWEB/backend/neko/browser-launch.sh || " + "{ cp -a /opt/douyinWEB/backend/neko/browser-launch.sh " + "/opt/douyinWEB/backend/neko/browser-launch.sh.bak.stoptrap_20260905 && " + "install -m 755 /tmp/browser-launch.sh.stoptrap /opt/douyinWEB/backend/neko/browser-launch.sh && " + "echo SYNCED_TRAP; }; grep -n on_supervisor_stop /opt/douyinWEB/backend/neko/browser-launch.sh | head", + timeout=30, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + print("local_sha", hashlib.sha256(data).hexdigest()[:12]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_selftest_asian_status_flap.py b/scripts/_selftest_asian_status_flap.py new file mode 100644 index 0000000..e5f32af --- /dev/null +++ b/scripts/_selftest_asian_status_flap.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Self-test: asian streetfood status stability + Studio preparing fields on dylive.""" +from __future__ import annotations + +import json +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +GID = "3fb8cbf7-2180-45bc-99f0-836169f0bf97" + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:200]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return code, out + + +c = ssh() +code, _ = run( + c, + r""" +set -euo pipefail +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json, time, http.cookiejar, urllib.request + +GID = "3fb8cbf7-2180-45bc-99f0-836169f0bf97" +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +login = urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(login, timeout=20) as r: + print("login", r.status, r.read()[:120]) + +seq = [] +for i in range(6): + with op.open("http://127.0.0.1:8014/api/youtube/relay/status", timeout=20) as r: + d = json.loads(r.read().decode()) + rows = d.get("groups") or d.get("relay_groups") or [] + row = next((x for x in rows if str(x.get("group_id")) == GID), {}) + seq.append({ + "i": i, + "biz": row.get("business_status"), + "row": row.get("status"), + "push": row.get("is_pushing"), + "pid": row.get("ffmpeg_pid") or 0, + "note": (row.get("business_note") or "")[:70], + }) + time.sleep(3.0) +print(json.dumps(seq, ensure_ascii=False, indent=2)) +biz = [x["biz"] for x in seq] +bad = ("monitoring" in biz and "streaming" in biz and biz[-1] == "monitoring") +print("unique_biz", sorted(set(str(x) for x in biz))) +print("bad_flap_back_to_monitoring", bad) + +from app import youtube_neko +sig = youtube_neko._cdp_studio_page_signals(7, force=True, max_age_sec=0.0) +print("cdp7", json.dumps({ + k: sig.get(k) for k in ( + "ok", "live_status", "on_air", "preparing_stream", "control_ready", + "health", "encoder_receiving", + ) +}, ensure_ascii=False)) +txt = str(sig.get("text") or "")[:180] +print("cdp_text", txt.replace("\n", " | ")) +PY +""", +) +c.close() +raise SystemExit(code) diff --git a/scripts/_selftest_end_stream_dylive.py b/scripts/_selftest_end_stream_dylive.py new file mode 100644 index 0000000..ffe474c --- /dev/null +++ b/scripts/_selftest_end_stream_dylive.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +"""Live self-test: CDP End Stream + confirm on dylive running Neko.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + return c + + +def run(c, cmd, t=120): + print(f"\n>>> {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return code, out + + +c = ssh() + +# 1) find running nekos + studio tabs +code, out = run( + c, + r""" +set -euo pipefail +echo '=== running nekos ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +echo '=== studio tabs on each running ===' +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + echo "-- $name" + docker exec "$name" python3 - <<'PY' || echo cdp_fail +import json,urllib.request +tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read()) +for t in tabs: + if t.get('type')!='page': continue + u=t.get('url') or '' + if 'studio.youtube.com' in u or 'google.com' in u: + print((t.get('title') or '')[:50], '|', u[:120]) +PY +done +""", + t=60, +) + +# 2) pick first running with livestreaming tab +code, out = run( + c, + r""" +set -euo pipefail +TARGET="" +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + hit=$(docker exec "$name" python3 - <<'PY' +import json,urllib.request +tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=5).read()) +for t in tabs: + u=(t.get('url') or '').lower() + if 'studio.youtube.com' in u and 'livestreaming' in u: + print('YES') + break +else: + print('NO') +PY +) + if [ "$hit" = "YES" ]; then TARGET="$name"; break; fi +done +echo "TARGET=$TARGET" +if [ -z "$TARGET" ]; then echo 'NO_LIVE_TAB'; exit 2; fi +echo "$TARGET" > /tmp/neko_end_target.txt + +# BEFORE scrape: does page have End dialog / End Stream / LIVE? +echo '=== BEFORE page signals ===' +docker exec -i "$TARGET" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tail -1 + +echo '=== RUN cdp_end_stream ===' +docker exec -i "$TARGET" python3 - < /opt/douyinWEB/backend/neko/cdp_end_stream.py | tee /tmp/cdp_end_result.json | tail -5 + +echo '=== AFTER page signals (sleep 3) ===' +sleep 3 +docker exec -i "$TARGET" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tee /tmp/cdp_after.json | tail -1 + +python3 - <<'PY' +import json +from pathlib import Path +end=json.loads(Path('/tmp/cdp_end_result.json').read_text(encoding='utf-8').strip().splitlines()[-1]) +after=json.loads(Path('/tmp/cdp_after.json').read_text(encoding='utf-8').strip().splitlines()[-1]) +print('RESULT_OK', end.get('ok')) +print('end_click', end.get('end_click')) +print('confirm_click', end.get('confirm_click')) +print('pre_confirm', end.get('pre_confirm')) +print('after_live_status', after.get('live_status'), 'on_air', after.get('on_air')) +# success criteria: confirm clicked OR already ended / not session live +cc=end.get('confirm_click') or {} +pre=end.get('pre_confirm') or {} +ok = bool(end.get('ok')) or bool(cc.get('ok')) or bool(pre.get('ok')) +status=str(after.get('live_status') or '') +if status in {'ended','waiting'} or after.get('on_air') is False: + ok = True +print('SELFTEST', 'PASS' if ok else 'FAIL') +PY +""", + t=90, +) + +c.close() +raise SystemExit(0 if "SELFTEST PASS" in out else 1) diff --git a/scripts/_selftest_graceful_end_neko7.py b/scripts/_selftest_graceful_end_neko7.py new file mode 100644 index 0000000..434e258 --- /dev/null +++ b/scripts/_selftest_graceful_end_neko7.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +"""Full graceful-end selftest on dylive neko-7 (avoid pkill matching this script).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + +# Upload runner script to avoid pkill -f matching inline heredoc with rtmps URL +runner = r'''#!/bin/bash +set -euo pipefail +NAME=douyinweb-neko-7 +NEKO_ID=7 +CHANNEL_PK=82102486-f5d7-434c-b508-4c6a10c5f325 + +echo '=== 1 BEFORE scrape ===' +docker exec -i "$NAME" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tee /tmp/before.json | python3 -c 'import sys,json;d=json.load(sys.stdin);print({k:d.get(k) for k in ("ok","live_status","on_air","health","url")})' + +echo '=== 2 stop ffmpeg by PID ===' +python3 - <<'PY' +import os, signal, subprocess +out=subprocess.check_output(["ps","-eo","pid,args"], text=True, errors="replace") +killed=0 +for line in out.splitlines(): + if "ffmpeg" in line and "youtube" in line.lower() and "python" not in line: + pid=int(line.split(None,1)[0]) + print("kill", pid, line[:120]) + try: + os.kill(pid, signal.SIGTERM) + killed+=1 + except ProcessLookupError: + pass +print("killed", killed) +PY +sleep 2 +pgrep -af '[f]fmpeg' | head -3 || echo 'ffmpeg_gone' + +echo '=== 3 wait encoder lost ===' +sleep 8 +docker exec -i "$NAME" python3 - < /opt/douyinWEB/backend/neko/cdp_studio_scrape.py | tee /tmp/mid.json | python3 -c 'import sys,json;d=json.load(sys.stdin);print({k:d.get(k) for k in ("ok","live_status","on_air","health")})' + +echo '=== 4 end_live_session ===' +cd /opt/douyinWEB/backend +./.venv/bin/python - < 20000 else out, flush=True) +c.close() +raise SystemExit(code) diff --git a/scripts/_smoke_dy_neko1.py b/scripts/_smoke_dy_neko1.py new file mode 100644 index 0000000..bc70558 --- /dev/null +++ b/scripts/_smoke_dy_neko1.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Smoke: API counts + start neko1 + probe HTTP.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.error +import urllib.request +import http.cookiejar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +BASE = "https://dy.nomadro.live" +ctx = ssl.create_default_context() +cj = http.cookiejar.CookieJar() +opener = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=ctx), +) + + +def api(path: str, method: str = "GET", data: dict | None = None): + body = None if data is None else json.dumps(data).encode() + headers = {"Content-Type": "application/json"} if data is not None else {} + req = urllib.request.Request(BASE + path, data=body, headers=headers, method=method) + with opener.open(req, timeout=120) as r: + return r.status, json.loads(r.read().decode()) + + +st, login = api("/api/auth/login", "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) +print("login", st, login) + +st, rooms = api("/api/rooms") +print("rooms", st, "n=", len(rooms.get("rooms") or []), "total=", rooms.get("total")) + +st, shorts = api("/api/shorts/channels") +chs = shorts.get("channels") or [] +with_rt = sum(1 for c in chs if c.get("refresh_token")) +print("shorts", st, "n=", len(chs), "with_rt=", with_rt) + +st, assign = api("/api/youtube/assign/groups") +groups = assign.get("groups") or assign.get("items") or [] +if isinstance(assign, list): + groups = assign +print("assign", st, "n=", len(groups), "sample=", [g.get("name") for g in groups[:5]]) + +# start neko 1 +print("--- start neko1 ---") +try: + st, out = api("/api/youtube/neko/1/start", "POST", {}) + print("start_api", st, out) +except Exception as e: + print("start_api_err", e) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + _, o, e2 = c.exec_command( + "docker start douyinweb-neko-1; sleep 4; docker ps --filter name=douyinweb-neko-1 --format '{{.Names}} {{.Status}}'", + timeout=90, + ) + print(o.read().decode()) + print(e2.read().decode()[:400]) + c.close() + +time.sleep(6) +st, status = api("/api/youtube/neko/status") +inst = next(i for i in status["instances"] if i["id"] == 1) +print("neko1", {k: inst.get(k) for k in ("running", "ready", "status", "http_port", "studio_url")}) +print("running_count", status.get("running"), "/", status.get("desired")) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +_, o, _ = c.exec_command( + "echo local:$(curl -sI -o /dev/null -w '%{http_code}' http://127.0.0.1:9200/); " + "echo pub:$(curl -skI -o /dev/null -w '%{http_code}' https://dy.nomadro.live/neko/1/); " + "ss -ulnp 2>/dev/null | grep -E '5200[0-9]|52300' | head -5 || true; " + "docker ps --filter name=douyinweb-neko-1 --format '{{.Names}} {{.Status}}'", + timeout=40, +) +print(o.read().decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_ssh_once_live.py b/scripts/_ssh_once_live.py new file mode 100644 index 0000000..575a1db --- /dev/null +++ b/scripts/_ssh_once_live.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Single SSH attempt + flush everything immediately. No long silent waits.""" +from __future__ import annotations + +import socket +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +HOST = "107.173.30.245" + + +def tcp(port, timeout=3.0): + s = socket.socket() + s.settimeout(timeout) + try: + s.connect((HOST, port)) + print(f"TCP {port}=OPEN", flush=True) + return True + except Exception as ex: + print(f"TCP {port}=CLOSED ({type(ex).__name__}: {ex})", flush=True) + return False + finally: + try: + s.close() + except Exception: + pass + + +print("=== port scan ===", flush=True) +for p in (22, 80, 443, 4014, 7000, 8014, 51820): + tcp(p) + +print("=== ssh once ===", flush=True) +t0 = time.time() +try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + HOST, + 22, + "root", + "Xiao4669805", + timeout=15, + banner_timeout=20, + auth_timeout=20, + allow_agent=False, + look_for_keys=False, + ) + print(f"SSH OK in {time.time()-t0:.1f}s", flush=True) + cmd = ( + "echo HI; uptime; free -h | head -2; " + "systemctl is-active caddy douyinweb-api douyinweb-web docker frpp 2>/dev/null; " + "ss -lntp 2>/dev/null | grep -E ':(443|80|8014|4015|4014)\\b' || true" + ) + _i, o, e = c.exec_command(cmd, timeout=40) + # stream-ish + while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.2) + sys.stdout.write(o.read().decode("utf-8", "replace")) + sys.stdout.write(e.read().decode("utf-8", "replace")) + sys.stdout.flush() + c.close() +except Exception as ex: + print(f"SSH FAIL in {time.time()-t0:.1f}s: {type(ex).__name__}: {ex}", flush=True) + raise SystemExit(1) + +print("DONE_ONCE", flush=True) diff --git a/scripts/_start_dylive_nekos.py b/scripts/_start_dylive_nekos.py new file mode 100644 index 0000000..17f4a4c --- /dev/null +++ b/scripts/_start_dylive_nekos.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Start all recreated Neko containers on dylive VPS (operator allowed recreate).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) + try: + cmd = r""" +set -e +echo '=== before ===' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +cd /opt/douyinWEB/backend +.venv/bin/python - <<'PY' +from app import youtube_neko +desired = max(1, youtube_neko._desired_from_db()) +print('desired', desired) +for i in range(1, desired + 1): + name = youtube_neko._container_name(i) + code, out = youtube_neko._run(['docker', 'start', name], timeout=90) + print(i, name, 'code', code, (out or '')[-120:]) +youtube_neko._open_firewall(desired) +youtube_neko.sync_nginx_proxy(desired) +print('firewall+nginx synced') +PY +echo '=== after ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +curl -sS -m 10 -o /dev/null -w 'dylive=%{http_code}\n' https://dylive.nomadro.com/api/health +""" + _i, o, e = c.exec_command(cmd, timeout=600) + print((o.read() + e.read()).decode("utf-8", "replace")) + return o.channel.recv_exit_status() + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_start_dylive_nekos2.py b/scripts/_start_dylive_nekos2.py new file mode 100644 index 0000000..2fdf156 --- /dev/null +++ b/scripts/_start_dylive_nekos2.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) +cmd = """ +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +echo --- +for i in 1 2 3 4 5 6 7; do + echo "start $i" + timeout 60 docker start douyinweb-neko-$i || echo "start_$i_fail" +done +sleep 2 +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +curl -sS -m 10 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health +cd /opt/douyinWEB && git rev-parse --short HEAD +""" +_i, o, e = c.exec_command(cmd, get_pty=True, timeout=420) +print(o.read().decode("utf-8", "replace")) +print(e.read().decode("utf-8", "replace")) +c.close() diff --git a/scripts/_start_dylive_nekos3.py b/scripts/_start_dylive_nekos3.py new file mode 100644 index 0000000..99d3562 --- /dev/null +++ b/scripts/_start_dylive_nekos3.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +last = None +for attempt in range(10): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + banner_timeout=180, + allow_agent=False, + look_for_keys=False, + ) + print("connected", attempt, flush=True) + cmd = ( + "docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'; " + "echo ---; " + "cd /opt/douyinWEB; git rev-parse --short HEAD; " + "curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "systemctl is-active douyinweb-api douyinweb-web" + ) + _i, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + # Start any exited containers one-by-one with timeout + _i, o, e = c.exec_command( + "for i in 1 2 3 4 5 6 7; do " + " st=$(docker inspect -f '{{.State.Status}}' douyinweb-neko-$i 2>/dev/null || echo missing); " + " echo neko-$i=$st; " + " if [ \"$st\" = exited ] || [ \"$st\" = created ]; then " + " timeout 45 docker start douyinweb-neko-$i && echo started_$i || echo fail_$i; " + " fi; " + "done; " + "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'", + timeout=420, + ) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + raise SystemExit(0) + except SystemExit: + raise + except Exception as ex: + last = ex + print("retry", attempt, type(ex).__name__, ex, flush=True) + time.sleep(10) + +raise SystemExit(f"ssh failed: {last}") diff --git a/scripts/_start_nomadro_live_next.sh b/scripts/_start_nomadro_live_next.sh new file mode 100644 index 0000000..32f537c --- /dev/null +++ b/scripts/_start_nomadro_live_next.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -e +echo '=== backend unit ===' +systemctl cat tiktok-promo-backend.service | head -40 +systemctl cat tiktok-promo-pocketbase.service 2>/dev/null | head -25 || true + +# Start Next + API (no live-router, no WP) +systemctl enable --now tiktok-promo-pocketbase.service 2>/dev/null || true +systemctl enable --now tiktok-promo-backend.service +systemctl enable --now tiktok-promo-frontend.service +systemctl restart tiktok-promo-frontend.service +systemctl restart tiktok-promo-backend.service 2>/dev/null || true +sleep 2 +systemctl is-active tiktok-promo-frontend.service tiktok-promo-backend.service || true +ss -lntp | grep -E ':3015|:8015' || true + +# Point Caddy default handle to Next :3015 (skip audience router) +cp -a /etc/caddy/sites/nomadro.live.caddy /etc/caddy/sites/nomadro.live.caddy.bak.next_$(date +%Y%m%d_%H%M%S) +python3 <<'PY' +from pathlib import Path +p = Path("/etc/caddy/sites/nomadro.live.caddy") +text = p.read_text(encoding="utf-8") +old = "reverse_proxy 127.0.0.1:4404" +new = "reverse_proxy 127.0.0.1:3015" +if old not in text: + raise SystemExit("expected 4404 upstream not found") +text = text.replace(old, new, 1) +# update comment +text = text.replace( + "# TikTok Promo Next.js + FastAPI, plus English WordPress via audience router.", + "# TikTok Promo Next.js + FastAPI (Next only; audience router / WP unused).", + 1, +) +p.write_text(text, encoding="utf-8") +print("patched nomadro.live.caddy") +print(p.read_text(encoding="utf-8")) +PY + +caddy validate --config /etc/caddy/Caddyfile +systemctl reload caddy +sleep 1 +systemctl is-active caddy +curl -sS -m 10 -o /dev/null -w 'local3015=%{http_code}\n' http://127.0.0.1:3015/ || true +curl -sS -m 10 -o /dev/null -w 'api=%{http_code}\n' http://127.0.0.1:8015/docs || true +curl -sS -m 15 -o /dev/null -w 'public=%{http_code}\n' -L https://nomadro.live/ || true +curl -sS -m 15 -o /dev/null -w 'www=%{http_code}\n' -L https://www.nomadro.live/ || true +systemctl is-active nomadro-live-router.service || echo 'router=inactive (ok)' +docker ps --format '{{.Names}} {{.Status}}' | grep -i 'live-wp\|wordpress' || true diff --git a/scripts/_start_nomadro_next_only.py b/scripts/_start_nomadro_next_only.py new file mode 100644 index 0000000..0064e1a --- /dev/null +++ b/scripts/_start_nomadro_next_only.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Start nomadro.com Next.js only; point edge to :4003; leave WP alone.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# Read-only peek then start — Caddy change only if currently pointing at router/WP +PROBE = r"""#!/bin/bash +echo '=== active caddy root ===' +head -80 /etc/caddy/Caddyfile +echo '---' +ls -la /etc/caddy/sites/*.caddy 2>/dev/null | grep -iE 'nomadro[^.]|nomadro\.caddy' || true +grep -n 'nomadro.com\|4403\|4003\|8088' /etc/caddy/Caddyfile 2>/dev/null | head -40 +# imported sites? +grep -n 'import\|nomadro' /etc/caddy/Caddyfile 2>/dev/null | head -20 +""" + +START = r"""#!/bin/bash +set -e +echo '=== start Next.js nomadro.service ===' +systemctl enable nomadro.service +systemctl restart nomadro.service +sleep 2 +systemctl is-active nomadro.service +ss -lntp | grep ':4003' || true +# Do NOT start nomadro-router (WP split) or WordPress containers +systemctl is-active nomadro-router.service 2>/dev/null || echo router=inactive +# Ensure Caddy apex points at Next :4003 (not router :4403 / WP :8088) +SITE=/etc/caddy/sites/nomadro.com.caddy +if [ ! -f "$SITE" ]; then + cat > "$SITE" <<'EOF' +www.nomadro.com { + redir https://nomadro.com{uri} permanent +} + +nomadro.com { + encode gzip + reverse_proxy 127.0.0.1:4003 +} +EOF + echo created $SITE +else + echo existing $SITE + cat "$SITE" +fi +# Ensure main Caddyfile imports sites +if ! grep -q 'sites/\*\.caddy\|sites/\*' /etc/caddy/Caddyfile 2>/dev/null; then + # check how other sites are loaded + grep -n import /etc/caddy/Caddyfile | head -10 +fi +caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20 +systemctl reload caddy +sleep 1 +curl -sS -m 10 -o /dev/null -w 'local4003=%{http_code}\n' http://127.0.0.1:4003/ || true +curl -sS -m 12 -o /dev/null -w 'public=%{http_code}\n' -L https://nomadro.com/ || true +curl -sS -m 12 -o /dev/null -w 'www=%{http_code}\n' -L https://www.nomadro.com/ || true +systemctl is-active nomadro.service caddy +# confirm WP containers left as-is (not started by us; may already be up) +docker ps --format '{{.Names}} {{.Status}}' | grep -i wordpress || echo 'no wp running (ok)' +""" + + +def run(c: paramiko.SSHClient, script: str, path: str, timeout: int = 120) -> str: + sftp = c.open_sftp() + with sftp.file(path, "w") as f: + f.write(script) + sftp.close() + _, o, e = c.exec_command(f"bash {path}", timeout=timeout) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out, flush=True) + return out + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + print("===== PROBE =====", flush=True) + run(c, PROBE, "/tmp/_probe_caddy_nomadro.sh", 40) + print("===== START =====", flush=True) + run(c, START, "/tmp/_start_nomadro_next_only.sh", 120) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_stop_dy_neko2_accidental.py b/scripts/_stop_dy_neko2_accidental.py new file mode 100644 index 0000000..adc402b --- /dev/null +++ b/scripts/_stop_dy_neko2_accidental.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Stop dy neko-2 we accidentally started during verify; leave prior runner alone.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) +_i, o, e = c.exec_command( + r""" +set +e +# Only stop if we just brought it up for TM check and nothing critical needs it. +# Operator had it Exited; restore that. Do NOT recreate. +docker stop douyinweb-neko-2 2>/dev/null || true +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +SEED='/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +echo -n 'dy_seed_markers='; grep -a -R -c 'YouTube Studio Auto Dismiss' "$SEED" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}' +""", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_stop_dylive_wp_umami_nsq.py b/scripts/_stop_dylive_wp_umami_nsq.py new file mode 100644 index 0000000..c3c000d --- /dev/null +++ b/scripts/_stop_dylive_wp_umami_nsq.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Stop WP / umami / nsq on dylive; leave douyinWEB + edge services alone.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +for i in range(8): + try: + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print("retry", i, e, flush=True) + time.sleep(2 + i) +else: + raise SystemExit("ssh fail") + +_i, o, e = c.exec_command( + r""" +set +e +echo '=== before (non-douyinweb) ===' +docker ps --format '{{.Names}}\t{{.Status}}' | grep -v douyinweb || true +free -m | head -2 + +# Match WP / umami / nsq only — do NOT touch ntfy, douyinweb, sing-box/frpp/wg +STOP_LIST=$(docker ps --format '{{.Names}}' | grep -E '^(nomadro-.*wp-|umami-|deploy-nsq)' || true) +echo "STOP_LIST=$STOP_LIST" + +if [ -n "$STOP_LIST" ]; then + docker stop $STOP_LIST +fi + +echo '=== after ===' +docker ps --format '{{.Names}}\t{{.Status}}' +echo '--- stopped targets ---' +docker ps -a --format '{{.Names}}\t{{.Status}}' | grep -E '^(nomadro-.*wp-|umami-|deploy-nsq)' || true +free -m | head -2 +# ensure neko-12 still up +docker ps --filter name=douyinweb-neko-12 --format '{{.Names}} {{.Status}}' +systemctl is-active sing-box frpp 'wg-quick@wg-dy' 2>/dev/null || true +""", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_stop_invalid_push_now.py b/scripts/_stop_invalid_push_now.py new file mode 100644 index 0000000..e1cba6b --- /dev/null +++ b/scripts/_stop_invalid_push_now.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +python3 <<'PY' +import sqlite3, time, signal, os, subprocess +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +now=time.time() +rows=con.execute("select group_id,status,ffmpeg_pid,push_seconds,error from yt_relay_states where status in ('pushing','starting','streaming')").fetchall() +print('pushing_rows', len(rows)) +for r in rows: + d=dict(r) + print(d) + pid=int(d.get('ffmpeg_pid') or 0) + if pid>0: + try: + os.kill(pid, signal.SIGTERM) + print('SIGTERM', pid) + except Exception as e: + print('kill_err', e) + con.execute( + "update yt_relay_states set status=?, error=?, ffmpeg_pid=0, speed=0, frame=0, updated_at=? where group_id=?", + ('waiting', '已停止:Studio NODATA/待开播(未 on_air)无效推流', now, d['group_id']), + ) +con.commit() +# leftover ffmpeg youtube +out=subprocess.check_output("ps -ef | grep -E '[f]fmpeg' | grep -iE 'rtmp|youtube' || true", shell=True, text=True) +print('ffmpeg_left', out[:800] or 'none') +for line in out.splitlines(): + parts=line.split() + if len(parts)>1 and parts[1].isdigit(): + try: + os.kill(int(parts[1]), signal.SIGKILL) + print('SIGKILL ffmpeg', parts[1]) + except Exception as e: + print(e) +PY +curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 160; echo +python3 <<'PY' +import sqlite3 +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +for r in con.execute("select group_id,status,ffmpeg_pid,substr(error,1,80) from yt_relay_states where group_id like '3fb8%' or status!='paused_exclusive' order by updated_at desc limit 6"): + print(r) +PY +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_stop_invalid2.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_stop_invalid2.sh", timeout=45) + o.channel.settimeout(40) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_stop_other_projects_confirm.py b/scripts/_stop_other_projects_confirm.py new file mode 100644 index 0000000..79ea134 --- /dev/null +++ b/scripts/_stop_other_projects_confirm.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Confirm other-project stacks are stopped; stop again if any revived.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +UNITS = [ + "nomadro.service", + "nomadro-api.service", + "nomadro-web.service", + "nomadro-router.service", + "nomadro-live-router.service", + "robook-api.service", + "robook-web.service", + "robook-pb.service", + "tiktok-promo-backend.service", + "tiktok-promo-frontend.service", + "tiktok-promo-pocketbase.service", + "xauto-web.service", + "xauto-pocketbase.service", + "ebook-api.service", + "hackrobot-web.service", +] + + +def connect(): + last = None + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + banner_timeout=180, + allow_agent=False, + look_for_keys=False, + ) + print("connected", i, flush=True) + return c + except Exception as ex: + last = ex + print("retry", i, type(ex).__name__, ex, flush=True) + time.sleep(6) + raise SystemExit(f"ssh failed: {last}") + + +def run(c, cmd, t=180): + print(f"\n$ {cmd[:220]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-7000:] if len(out) > 7000 else out, flush=True) + return code, out + + +def main() -> int: + c = connect() + try: + units = " ".join(UNITS) + run(c, f"systemctl stop {units}; systemctl disable {units}; echo OK", 240) + run( + c, + "echo '=== status ==='; " + + "".join( + f'printf "%-42s active=%-12s enabled=%s\\n" "{u}" "$(systemctl is-active {u} 2>/dev/null)" "$(systemctl is-enabled {u} 2>/dev/null)"; ' + for u in UNITS + ), + 120, + ) + run(c, "uptime; free -h | head -2") + print("DONE", flush=True) + return 0 + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_studio_samples_ro.py b/scripts/_studio_samples_ro.py new file mode 100644 index 0000000..f3f1428 --- /dev/null +++ b/scripts/_studio_samples_ro.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +python3 - <<'PY' +import sqlite3, time +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +now=time.time() +print('now', now) +rows=con.execute('SELECT * FROM yt_studio_samples ORDER BY ts DESC LIMIT 12').fetchall() +for r in rows: + d=dict(r) + age=now-float(d.get('ts') or 0) + print(f"age={age:.0f}s kind={d.get('neko_kind')} ref={d.get('neko_ref')} on_air={d.get('on_air')} page={d.get('live_page_open')} status={d.get('live_status')} health={d.get('health')} group={str(d.get('group_id') or '')[:8]} url={(d.get('studio_url') or '')[:70]}") + +print('=== relay state group7 detail ===') +r=con.execute("SELECT * FROM yt_relay_states WHERE group_id='3fb8cbf7-2180-45bc-99f0-836169f0bf97'").fetchone() +if r: + d=dict(r) + for k in sorted(d.keys()): + v=d[k] + if isinstance(v,str) and len(v)>200: v=v[:200]+'...' + print(f" {k}={v}") +PY +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_studio_samples_ro.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_studio_samples_ro.sh", timeout=30) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_sync_browser_launch_inplace.py b/scripts/_sync_browser_launch_inplace.py new file mode 100644 index 0000000..f088257 --- /dev/null +++ b/scripts/_sync_browser_launch_inplace.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""In-place overwrite browser-launch.sh so Docker bind-mounts see the new content.""" +from __future__ import annotations + +import hashlib +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend/neko/browser-launch.sh" +REMOTE = "/opt/douyinWEB/backend/neko/browser-launch.sh" + +REMOTE_SH = r"""#!/bin/bash +set -e +REMOTE=/opt/douyinWEB/backend/neko/browser-launch.sh +test -f "$REMOTE" +cp -a "$REMOTE" "${REMOTE}.bak.inplace_$(date +%Y%m%d_%H%M%S)" || true +# overwrite same inode — DO NOT use install/mv (breaks docker bind mounts) +cat /tmp/browser-launch.sh.stoptrap > "$REMOTE" +chmod 755 "$REMOTE" +echo "HOST_LINES=$(wc -l < "$REMOTE")" +grep -n on_supervisor_stop "$REMOTE" | head +for N in $(docker ps --format '{{.Names}}' | grep -E 'neko' | sort); do + lines=$(docker exec "$N" wc -l /etc/neko/browser-launch.sh 2>/dev/null | awk '{print $1}' || echo na) + trap=$(docker exec "$N" grep -c on_supervisor_stop /etc/neko/browser-launch.sh 2>/dev/null || echo 0) + echo "$N lines=$lines trap=$trap" +done +""" + + +def run(host: str, port: int, user: str, password: str, sudo: bool) -> None: + data = LOCAL.read_bytes() + print(f"\n===== {user}@{host}:{port} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + host, + port, + user, + password, + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/browser-launch.sh.stoptrap", "wb") as f: + f.write(data) + with sftp.file("/tmp/_inplace_browser_launch.sh", "w") as f: + f.write(REMOTE_SH) + sftp.close() + if sudo: + cmd = f"echo '{password}' | sudo -S -p '' bash /tmp/_inplace_browser_launch.sh" + else: + cmd = "bash /tmp/_inplace_browser_launch.sh" + _i, o, e = c.exec_command(cmd, timeout=180) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + print("local_sha", hashlib.sha256(data).hexdigest()[:12], "lines", data.count(b"\n")) + + +def main() -> None: + run("107.173.30.245", 4014, "eric", "4669805", sudo=True) + run("107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/_sync_browser_launch_stoptrap.py b/scripts/_sync_browser_launch_stoptrap.py new file mode 100644 index 0000000..0f24db0 --- /dev/null +++ b/scripts/_sync_browser_launch_stoptrap.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Sync browser-launch.sh to physical host (bind-mounted into assign Nekos).""" +from __future__ import annotations + +import hashlib +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +LOCAL = ROOT / "backend/neko/browser-launch.sh" +REMOTE = "/opt/douyinWEB/backend/neko/browser-launch.sh" + + +def main() -> None: + data = LOCAL.read_bytes() + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + sftp = c.open_sftp() + with sftp.file("/tmp/browser-launch.sh.stoptrap", "w") as f: + f.write(data) + sftp.close() + _i, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' bash -lc " + f"'cp -a {REMOTE} {REMOTE}.bak.stoptrap_20260905 && " + f"install -m 755 /tmp/browser-launch.sh.stoptrap {REMOTE} && " + f"sha256sum {REMOTE} && grep -n on_supervisor_stop {REMOTE} | head'", + timeout=30, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + print("local_sha", hashlib.sha256(data).hexdigest()[:12]) + + +if __name__ == "__main__": + main() diff --git a/scripts/_sync_dy_browser_launch_clean.py b/scripts/_sync_dy_browser_launch_clean.py new file mode 100644 index 0000000..4a6b97f --- /dev/null +++ b/scripts/_sync_dy_browser_launch_clean.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Sync cleaned browser-launch.sh to dy; refresh chrome only if running.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +raw = ( + Path(__file__).resolve().parents[1] / "backend" / "neko" / "browser-launch.sh" +).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") +assert b"--jitless" in raw and b"--no-wasm-simd" not in raw + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=60, + allow_agent=False, + look_for_keys=False, + banner_timeout=300, +) +sftp = c.open_sftp() +with sftp.file("/opt/douyinWEB/backend/neko/browser-launch.sh", "wb") as f: + f.write(raw) +sftp.chmod("/opt/douyinWEB/backend/neko/browser-launch.sh", 0o755) +sftp.close() + +_i, o, e = c.exec_command( + r""" +set +e +# overwrite inodes of any running neko mounts +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-'); do + INO=$(docker exec "$name" sh -c 'ls -li /etc/neko/browser-launch.sh' 2>/dev/null | awk '{print $1}') + [ -z "$INO" ] && continue + MATCH=$(find /opt /root -xdev -inum "$INO" 2>/dev/null | head -1) + if [ -n "$MATCH" ]; then + cat /opt/douyinWEB/backend/neko/browser-launch.sh > "$MATCH" + echo FIXED_$name inode=$INO + else + echo PATHONLY_$name + fi + docker exec "$name" sh -c 'grep -n js-flags /etc/neko/browser-launch.sh | head -1' + # restart chrome only if currently RUNNING + if docker exec "$name" supervisorctl status google-chrome 2>/dev/null | grep -q RUNNING; then + docker exec "$name" sh -c 'rm -f /home/neko/.config/google-chrome/Singleton*; supervisorctl restart google-chrome' + sleep 8 + docker exec "$name" supervisorctl status google-chrome + docker exec "$name" curl -sS -m 3 http://127.0.0.1:9222/json/version | head -c 120; echo + else + echo SKIP_chrome_$name + fi +done +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +""", + timeout=240, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() +print("DONE") diff --git a/scripts/_sync_exclude_vps_to_phys.py b/scripts/_sync_exclude_vps_to_phys.py new file mode 100644 index 0000000..797dcd2 --- /dev/null +++ b/scripts/_sync_exclude_vps_to_phys.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +"""Copy timeslot exclude list from VPS → physical for dual-deploy parity.""" +from __future__ import annotations + +import json +import urllib.request +import http.cookiejar + +import paramiko + + +def api(port, user, pwd, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pwd, timeout=25) + return c + + +GET_SCRIPT = r''' +import json,urllib.request,http.cookiejar +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +op.open(req, timeout=15) +p=json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=30).read()) +print(json.dumps({"count":p.get("count"),"text":p.get("text") or ""}, ensure_ascii=False)) +''' + +SET_TMPL = r''' +import json,urllib.request,http.cookiejar +TEXT = %r +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +op.open(req, timeout=15) +req=urllib.request.Request("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", data=json.dumps({"text": TEXT}).encode(), headers={"Content-Type":"application/json"}, method="POST") +p=json.loads(op.open(req, timeout=60).read()) +print("saved", p.get("count"), "dup", p.get("skipped_dup"), "invalid", p.get("skipped_invalid")) +st=json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=30).read()) +print("now", st.get("count"), "effective", st.get("effective_room_count")) +''' + + +def py_run(c, code, sudo_pw=None): + if sudo_pw: + sftp = c.open_sftp() + with sftp.file("/tmp/_exsync.py", "w") as f: + f.write(code) + sftp.close() + _, o, e = c.exec_command( + f"echo '{sudo_pw}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_exsync.py", + timeout=90, + ) + else: + _, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -", timeout=90) + o.channel.sendall(code.encode()) + o.channel.shutdown_write() + out = o.read().decode("utf-8", "replace") + err = e.read().decode("utf-8", "replace") + return out, err + + +def main(): + # get from VPS + v = api(22, "root", "Xiao4669805") + out, err = py_run(v, GET_SCRIPT) + v.close() + data = json.loads(out.strip().splitlines()[-1]) + text = data.get("text") or "" + print("vps exclude count", data.get("count"), "chars", len(text)) + if not text.strip(): + print("nothing to sync") + return + # set on physical + p = api(4014, "eric", "4669805") + out2, err2 = py_run(p, SET_TMPL % text, sudo_pw="4669805") + print(out2) + if err2.strip(): + print(err2[-400:]) + p.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_sync_fill_dylive_keys.py b/scripts/_sync_fill_dylive_keys.py new file mode 100644 index 0000000..3978d09 --- /dev/null +++ b/scripts/_sync_fill_dylive_keys.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +"""Inspect stream-keys + assign key coverage; sync registry dy→dylive if needed.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.request +from http.cookiejar import CookieJar +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() +SSH_PASS = "Xiao4669805" +APP_PASS = "Xiao4669805@" + + +def http_login(base: str): + cj = CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": APP_PASS}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + op.open(req, timeout=45).read() + return op + + +def get_json(op, url: str): + with op.open(url, timeout=45) as r: + return r.status, json.loads(r.read().decode()) + + +def ssh(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + SSH_PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("ssh_retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh fail {host}") + + +def run(c, cmd: str, t: int = 120) -> str: + _i, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def summarize(label: str, base: str): + print(f"\n=== HTTP {label} ===", flush=True) + op = http_login(base) + st, sk = get_json(op, f"{base}/api/youtube/stream-keys") + print("stream-keys keys:", sorted(sk.keys()) if isinstance(sk, dict) else type(sk), "status", st) + entries = [] + if isinstance(sk, dict): + for k in ("entries", "items", "keys", "data"): + if isinstance(sk.get(k), list): + entries = sk[k] + break + if not entries and all(isinstance(v, dict) for v in sk.values()): + entries = list(sk.values()) + print(f" entries={len(entries)}") + for e in entries[:3]: + if isinstance(e, dict): + print( + " sample", + e.get("title") or e.get("channel_title") or e.get("label"), + "cid=", + (e.get("youtube_channel_id") or "")[:24], + "sk_len=", + len(str(e.get("stream_key") or "")), + ) + + st, ag = get_json(op, f"{base}/api/youtube/assign/groups") + groups = ag.get("groups") if isinstance(ag, dict) else [] + print(f"assign groups={len(groups)} status={st}") + missing = [] + for g in groups: + skv = str(g.get("stream_key") or "") + title = g.get("title") or g.get("channel_title") or g.get("id") + print( + f" - {(title or '')[:40]!s} sk_len={len(skv)} cid={(g.get('youtube_channel_id') or '')[:20]}" + ) + if len(skv) < 12: + missing.append(title) + print("missing_or_short:", missing) + return entries, groups + + +dy_entries, dy_groups = summarize("dy", "https://dy.nomadro.live") +dl_entries, dl_groups = summarize("dylive", "https://dylive.nomadro.com") + +# export registry from dy via SSH (authoritative) +print("\n=== SSH export dy registry ===", flush=True) +dy = ssh("108.174.50.68") +out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db, yt_assign_db +exp = yt_stream_key_db.export_all() +print('REG_START') +print(json.dumps(exp, ensure_ascii=False)) +print('REG_END') +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +print('ASSIGN_START') +print(json.dumps([{ + 'id': g.get('id'), + 'name': g.get('name'), + 'title': g.get('title') or g.get('name'), + 'youtube_channel_id': g.get('youtube_channel_id'), + 'stream_key': g.get('stream_key'), + 'stream_key_len': len(str(g.get('stream_key') or '')), +} for g in gs], ensure_ascii=False)) +print('ASSIGN_END') +print('reg_count', len((exp.get('items') or exp.get('entries') or []))) +PY +""", +) +dy.close() +print(out[-3000:], flush=True) + +a = out.find("REG_START") +b = out.find("REG_END") +assert a >= 0 and b > a +reg = json.loads(out[a + len("REG_START") : b].strip()) +c0 = out.find("ASSIGN_START") +c1 = out.find("ASSIGN_END") +assign_rows = json.loads(out[c0 + len("ASSIGN_START") : c1].strip()) + +# import to dylive +print("\n=== import registry + fill missing assign keys on dylive ===", flush=True) +dl = ssh("107.173.30.245") +sftp = dl.open_sftp() +with sftp.file("/tmp/dy_stream_key_export.json", "w") as f: + f.write(json.dumps(reg, ensure_ascii=False)) +with sftp.file("/tmp/dy_assign_keys.json", "w") as f: + f.write(json.dumps(assign_rows, ensure_ascii=False)) +sftp.close() + +print( + run( + dl, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_stream_key_db, yt_assign_db + +with open('/tmp/dy_stream_key_export.json', encoding='utf-8') as f: + reg = json.load(f) +items = reg.get('items') or reg.get('entries') or [] +print('import_result', yt_stream_key_db.import_payload(items, replace=False)) + +with open('/tmp/dy_assign_keys.json', encoding='utf-8') as f: + rows = json.load(f) +by_cid = {str(r.get('youtube_channel_id') or ''): r for r in rows if r.get('youtube_channel_id')} +by_title = {str(r.get('title') or ''): r for r in rows} +by_name = {str(r.get('name') or ''): r for r in rows} +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +filled = 0 +for g in gs: + sk = str(g.get('stream_key') or '') + if len(sk) >= 12: + continue + src = ( + by_cid.get(str(g.get('youtube_channel_id') or '')) + or by_title.get(str(g.get('title') or '')) + or by_name.get(str(g.get('name') or '')) + ) + if not src or len(str(src.get('stream_key') or '')) < 12: + print('NO_SRC', g.get('name') or g.get('title'), g.get('youtube_channel_id')) + continue + gid = g['id'] + new_sk = src['stream_key'] + try: + yt_assign_db.update_group(gid, stream_key=new_sk) + filled += 1 + print('FILLED', g.get('name') or g.get('title'), 'len', len(new_sk)) + except Exception as e: + print('FAIL', g.get('name'), e) + +listed = yt_stream_key_db.list_entries(include_secret=True) +print('registry_total', listed.get('total'), 'items', len(listed.get('items') or [])) +print('filled', filled) +gs2 = yt_assign_db.list_groups(include_urls=False, include_secret=True) +full = sum(1 for g in gs2 if len(str(g.get('stream_key') or '')) >= 12) +print('assign_full', full, 'of', len(gs2)) +for g in gs2: + print(' ', (g.get('name') or g.get('title') or '')[:36], 'sk', len(str(g.get('stream_key') or ''))) +PY +""", + t=180, + ), + flush=True, +) +dl.close() +print("DONE") diff --git a/scripts/_sync_missing_assign_dylive.py b/scripts/_sync_missing_assign_dylive.py new file mode 100644 index 0000000..8b5d57f --- /dev/null +++ b/scripts/_sync_missing_assign_dylive.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Create missing assign groups on dylive from dy (china/nice street food).""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +SSH_PASS = "Xiao4669805" +NEED = {"china street food", "nice street food"} + + +def ssh(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + SSH_PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit("ssh fail") + + +def run(c, cmd: str, t: int = 180) -> str: + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-8000:] if len(out) > 8000 else out, flush=True) + return out + + +dy = ssh("108.174.50.68") +out = run( + dy, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_assign_db +gs = yt_assign_db.list_groups(include_urls=True, include_secret=True) +need = {'china street food', 'nice street food'} +picked = [] +for g in gs: + if str(g.get('name') or '') in need: + picked.append({ + 'name': g.get('name'), + 'channel_pk': g.get('channel_pk') or '', + 'youtube_channel_id': g.get('youtube_channel_id') or '', + 'stream_key': g.get('stream_key') or '', + 'note': g.get('note') or '', + 'enabled': bool(g.get('enabled', True)), + 'category': g.get('category') or 'normal', + 'pool': [{'url': p.get('url'), 'title': p.get('title') or '', 'room_id': p.get('room_id') or ''} for p in (g.get('pool') or []) if p.get('url')], + 'featured': [{'url': p.get('url'), 'title': p.get('title') or '', 'room_id': p.get('room_id') or ''} for p in (g.get('featured') or []) if p.get('url')], + 'slots': [{ + 'url': p.get('url'), 'title': p.get('title') or '', 'room_id': p.get('room_id') or '', + 'weekday': p.get('weekday'), 'start_minute': p.get('start_minute'), 'end_minute': p.get('end_minute'), + } for p in (g.get('slots') or [])], + }) +print('PICK_START') +print(json.dumps(picked, ensure_ascii=False)) +print('PICK_END') +print('picked', len(picked)) +PY +""", +) +dy.close() +a, b = out.find("PICK_START"), out.find("PICK_END") +assert a >= 0 and b > a +picked = json.loads(out[a + len("PICK_START") : b].strip()) +print(f"got {len(picked)} groups", flush=True) + +dl = ssh("107.173.30.245") +sftp = dl.open_sftp() +with sftp.file("/tmp/dy_missing_assign.json", "w") as f: + f.write(json.dumps(picked, ensure_ascii=False)) +sftp.close() +run( + dl, + r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import json +from app import yt_assign_db + +with open('/tmp/dy_missing_assign.json', encoding='utf-8') as f: + picked = json.load(f) + +existing = {str(g.get('name') or ''): g for g in yt_assign_db.list_groups(include_urls=False, include_secret=True)} +by_cid = {str(g.get('youtube_channel_id') or ''): g for g in existing.values()} + +for src in picked: + name = src['name'] + ycid = src.get('youtube_channel_id') or '' + if name in existing or (ycid and ycid in by_cid): + print('SKIP_EXISTS', name, ycid) + # still fill stream key if empty + g = existing.get(name) or by_cid.get(ycid) + if g and len(str(g.get('stream_key') or '')) < 12 and len(str(src.get('stream_key') or '')) >= 12: + yt_assign_db.update_group(g['id'], stream_key=src['stream_key']) + print(' filled_key', name) + continue + try: + g = yt_assign_db.create_group( + name=name, + channel_pk=src.get('channel_pk') or '', + youtube_channel_id=ycid, + stream_key=src.get('stream_key') or '', + note=src.get('note') or '', + enabled=bool(src.get('enabled', True)), + category=src.get('category') or 'normal', + ) + print('CREATED', name, g.get('id'), 'neko', g.get('neko_instance_id')) + gid = g['id'] + pool_urls = [p['url'] for p in (src.get('pool') or []) if p.get('url')] + if pool_urls: + try: + r = yt_assign_db.add_pool_urls(gid, urls=pool_urls) + print(' pool', r) + except Exception as e: + print(' pool_fail', e) + feat_urls = [p['url'] for p in (src.get('featured') or []) if p.get('url')] + if feat_urls: + # featured needs pool ids — re-list and match + try: + g2 = yt_assign_db.get_group(gid) or {} + pool = g2.get('pool') or [] + ids = [] + want = set(feat_urls) + for p in pool: + if p.get('url') in want: + ids.append(p['id']) + if ids: + print(' featured', yt_assign_db.add_featured(gid, ids)) + except Exception as e: + print(' feat_fail', e) + # slots: skip structured copy (needs pool_url_ids); operator can re-fill + if src.get('slots'): + print(' slots_src', len(src['slots']), '(not auto-copied)') + except Exception as e: + print('CREATE_FAIL', name, e) + +gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) +print('TOTAL', len(gs)) +for g in gs: + print('-', g.get('name'), 'sk', len(str(g.get('stream_key') or '')), 'neko', g.get('neko_instance_id'), 'en', g.get('neko_enabled')) +PY +""", +) +dl.close() +print("DONE") diff --git a/scripts/_sync_neko_cdp_dylive.py b/scripts/_sync_neko_cdp_dylive.py new file mode 100644 index 0000000..4d96966 --- /dev/null +++ b/scripts/_sync_neko_cdp_dylive.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +import hashlib +import sys +from pathlib import Path +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +data = Path(r"c:\Users\admin\Desktop\douyinWEB\backend\app\youtube_neko.py").read_bytes() +print("hash", hashlib.sha256(data).hexdigest()[:12], flush=True) +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/opt/douyinWEB/backend/app/youtube_neko.py", "wb") as f: + f.write(data) +sftp.close() +_i, o, e = c.exec_command( + "systemctl restart douyinweb-api; sleep 2; systemctl is-active douyinweb-api; " + "grep -c 'relay may leave Chrome' /opt/douyinWEB/backend/app/youtube_neko.py", + timeout=60, +) +print(o.read().decode(), flush=True) +print(e.read().decode()[:400], flush=True) +c.close() +print("dylive_ok", flush=True) diff --git a/scripts/_sync_tm_script_seed_dual.py b/scripts/_sync_tm_script_seed_dual.py new file mode 100644 index 0000000..5808ca7 --- /dev/null +++ b/scripts/_sync_tm_script_seed_dual.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Sync TM script seed dylive→local→dy; verify running nekos.""" +from __future__ import annotations + +import io +import sys +import tarfile +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +TM = "dhdgffkkebhmkfjojejmpbldmpobfkfo" +SEED_REL = f"backend/neko/tampermonkey-seed/Default/Local Extension Settings/{TM}" + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect( + host, + 22, + "root", + PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", host, i, e, flush=True) + time.sleep(2) + raise SystemExit(f"ssh fail {host}") + + +def run(c, cmd: str, t: int = 300) -> str: + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-12000:] if len(out) > 12000 else out, flush=True) + return out + + +# 1) pull seed tarball from dylive +print("=== pull seed from dylive ===", flush=True) +dl = connect("107.173.30.245") +run( + dl, + r""" +set -e +SEED='/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +test -d "$SEED" +grep -a -R -q 'YouTube Studio Auto Dismiss' "$SEED" +tar -C '/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings' \ + -czf /tmp/tm_script_seed.tgz dhdgffkkebhmkfjojejmpbldmpobfkfo +ls -lh /tmp/tm_script_seed.tgz +# verify running +for name in douyinweb-neko-2 douyinweb-neko-19; do + docker exec "$name" sh -c 'python3 -c " +import os,re +p=\"/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo\" +b=b\"\" +for r,_,fs in os.walk(p): + for f in fs: + try: b+=open(os.path.join(r,f),\"rb\").read() + except: pass +print(\"'"$name"'\", \"markers\", len(re.findall(\"YouTube Studio Auto Dismiss\", b.decode(\"latin1\",\"ignore\"))), \"blob\", len(b)) +"' + docker exec "$name" supervisorctl status google-chrome | head -1 +done +""", +) +sftp = dl.open_sftp() +buf = io.BytesIO() +sftp.getfo("/tmp/tm_script_seed.tgz", buf) +sftp.close() +dl.close() +print(f"downloaded {buf.tell()} bytes", flush=True) + +# 2) extract into local repo +local_dir = ROOT / "backend/neko/tampermonkey-seed/Default/Local Extension Settings" +local_dir.mkdir(parents=True, exist_ok=True) +buf.seek(0) +with tarfile.open(fileobj=buf, mode="r:gz") as tf: + tf.extractall(local_dir) +local_tm = local_dir / TM +assert local_tm.is_dir() +# quick marker check +blob = b"" +for p in local_tm.rglob("*"): + if p.is_file(): + blob += p.read_bytes() +assert b"YouTube Studio Auto Dismiss" in blob, "local seed missing script" +print(f"local seed ok markers bytes={len(blob)}", flush=True) + +# 3) push to dy + repair empty profiles +print("=== sync to dy + repair profiles ===", flush=True) +dy = connect("108.174.50.68") +sftp = dy.open_sftp() +buf.seek(0) +with sftp.file("/tmp/tm_script_seed.tgz", "wb") as f: + f.write(buf.getvalue()) +sftp.close() +run( + dy, + r""" +set -euo pipefail +TM=dhdgffkkebhmkfjojejmpbldmpobfkfo +SEED="/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings/$TM" +BASE=/opt/douyinWEB/backend/data/neko/profiles +mkdir -p "$(dirname "$SEED")" +ts=$(date +%s) +if [ -d "$SEED" ]; then mv "$SEED" "$SEED.bak-$ts"; fi +tar -C "/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings" -xzf /tmp/tm_script_seed.tgz +grep -a -R -q 'YouTube Studio Auto Dismiss' "$SEED" +echo seed_ok + +# pick GOOD = seed +GOOD="$SEED" +for d in "$BASE"/*; do + [ -d "$d" ] || continue + id=$(basename "$d") + p="$d/Default/Local Extension Settings/$TM" + markers=$(grep -a -R -c 'YouTube Studio Auto Dismiss' "$p" 2>/dev/null | awk -F: '{s+=$2} END{print s+0}') + bytes=$(du -sb "$p" 2>/dev/null | awk '{print $1}') + need=0 + [ ! -d "$p" ] && need=1 + [ "${markers:-0}" -lt 1 ] && need=1 + [ "${bytes:-0}" -lt 8000 ] && need=1 + if [ "$need" != 1 ]; then + echo OK id=$id markers=$markers + continue + fi + echo REPAIR id=$id + name=douyinweb-neko-$id + running=0 + if docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null | grep -q true; then + running=1 + docker exec "$name" supervisorctl stop google-chrome 2>/dev/null || true + sleep 1 + fi + mkdir -p "$(dirname "$p")" + if [ -d "$p" ]; then mv "$p" "$p.bak-empty-$ts"; fi + cp -a "$GOOD" "$p" + rm -f "$p/LOCK" + chown -R 1000:1000 "$p" 2>/dev/null || true + if [ "$running" = 1 ]; then + docker exec "$name" sh -c "rm -f /home/neko/.config/google-chrome/Singleton*; chown -R neko:neko '/home/neko/.config/google-chrome/Default/Local Extension Settings/$TM'; rm -f '/home/neko/.config/google-chrome/Default/Local Extension Settings/$TM/LOCK'; supervisorctl start google-chrome" + sleep 5 + docker exec "$name" supervisorctl status google-chrome | head -1 + fi +done + +echo '=== dy running ===' +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + docker exec "$name" python3 -c " +import os,re +p='/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +b=b'' +for r,_,fs in os.walk(p): + for f in fs: + try: b+=open(os.path.join(r,f),'rb').read() + except: pass +print('$name', 'markers', len(re.findall('YouTube Studio Auto Dismiss', b.decode('latin1','ignore'))), 'blob', len(b)) +" 2>/dev/null || echo "$name check_fail" +done +echo DY_DONE +""", +) +dy.close() +print("ALL_DONE") diff --git a/scripts/_test_hysteria5_no_hop.py b/scripts/_test_hysteria5_no_hop.py new file mode 100644 index 0000000..172f2e5 --- /dev/null +++ b/scripts/_test_hysteria5_no_hop.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Test: remove hysteria ports hop temporarily and re-delay.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected guest", flush=True) + +cmd = r''' +echo 4669805 | sudo -S -p '' bash -lc ' +set -e +# backup runtime config +cp -a /tmp/ShellCrash/config.yaml /tmp/ShellCrash/config.yaml.bak.hysteria_ports +# remove ONLY the ports line under hysteria5 block (first occurrence after the name) +python3 - <", o.channel.recv_exit_status(), flush=True) +c.close() +print("DONE", flush=True) diff --git a/scripts/_test_hysteria5_no_hop2.py b/scripts/_test_hysteria5_no_hop2.py new file mode 100644 index 0000000..10e8328 --- /dev/null +++ b/scripts/_test_hysteria5_no_hop2.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Continue hysteria5 no-hop test after config edit.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False) +print("connected", flush=True) +cmd = r''' +echo 4669805 | sudo -S -p '' bash -lc ' +grep -A12 "name: 1d2da142-singbox_hysteria5" /tmp/ShellCrash/config.yaml | head -14 +systemctl restart shellcrash.service +sleep 5 +systemctl is-active shellcrash +curl -sS -m 5 http://127.0.0.1:9999/version; echo +curl -sS -m 15 -G "http://127.0.0.1:9999/proxies/1d2da142-singbox_hysteria5/delay" --data-urlencode "url=http://www.gstatic.com/generate_204" --data-urlencode "timeout=8000"; echo +curl -sS -m 10 -G "http://127.0.0.1:9999/proxies/1d2da142-singbox_tuic5/delay" --data-urlencode "url=http://www.gstatic.com/generate_204" --data-urlencode "timeout=5000"; echo +' +''' +_i, o, e = c.exec_command(cmd, timeout=90) +while not o.channel.exit_status_ready(): + if o.channel.recv_ready(): + sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace")) + sys.stdout.flush() + if o.channel.recv_stderr_ready(): + sys.stdout.write(o.channel.recv_stderr(4096).decode("utf-8", "replace")) + sys.stdout.flush() + time.sleep(0.1) +sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace")) +sys.stdout.flush() +print("->", o.channel.recv_exit_status(), flush=True) +c.close() +print("DONE", flush=True) diff --git a/scripts/_tmp_analyze_shellcrash_tuic.py b/scripts/_tmp_analyze_shellcrash_tuic.py new file mode 100644 index 0000000..d31172a --- /dev/null +++ b/scripts/_tmp_analyze_shellcrash_tuic.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +"""Read-only: current ShellClash/TUIC/VLESS selection on phys + VPS.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar as cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(base, path, op=None, timeout=40): + req = urllib.request.Request(base + path, headers={"Content-Type": "application/json"}) + opener = op or urllib.request.build_opener() + with opener.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def login(base): + cj = cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=25) + return op + + +def ssh_probe(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=60): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + print(run( + "grep -E 'DY_SHELLCRASH|DEFAULT_NODE|VLESS|TUIC' /etc/systemd/system/douyinweb-api.service " + "/etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | sed -n '1,40p'" + )) + print(run( + "grep -nE 'default_node|VLESS|TUIC|pick_best|hy2|hysteria|tuic' " + "/opt/douyinWEB/backend/app/shellcrash_hub.py 2>/dev/null | sed -n '1,40p'" + )) + # clash API now-node if available + print(run( + "curl -sS -m 5 http://127.0.0.1:9999/proxies 2>/dev/null | python3 -c " + "\"import sys,json; d=json.load(sys.stdin); " + "ps=d.get('proxies') or {}; " + "keys=['GLOBAL','PROXY','Select','自动选择','节点选择','FINAL']; " + "[print(k, (ps.get(k) or {}).get('now'), (ps.get(k) or {}).get('type')) for k in keys if k in ps]; " + "nows=[(k,v.get('now')) for k,v in ps.items() if isinstance(v,dict) and v.get('type')=='Selector']; " + "print('selectors', len(nows)); " + "[print(' ',k,n) for k,n in nows[:12]]\" 2>/dev/null || echo no_clash_api" + )) + print(run( + "python3 - <<'PY'\n" + "import re\n" + "from pathlib import Path\n" + "for p in [Path('/tmp/ShellCrash/config.yaml'), Path('/opt/douyinWEB/backend/data/shellcrash/config.yaml')]:\n" + " if not p.exists():\n" + " print('missing', p); continue\n" + " t=p.read_text(encoding='utf-8',errors='replace')\n" + " print(p, 'len', len(t))\n" + " for pat in ['tuic','hysteria','vless','interface-name']:\n" + " print(' ',pat, len(re.findall(pat,t,re.I)))\n" + "PY" + )) + c.close() + + +for base in ["https://dy.nomadro.com", "https://dylive.nomadro.com"]: + try: + op = login(base) + for path in [ + "/api/network/shellcrash/status", + "/api/network/status", + ]: + try: + d = call(base, path, op, timeout=35) + # scrub secrets + s = json.dumps(d, ensure_ascii=False)[:500] + print(base, path, s) + except Exception as ex: + print(base, path, "ERR", ex) + except Exception as ex: + print(base, "login ERR", ex) + +ssh_probe("PHYS", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +ssh_probe("VPS", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) diff --git a/scripts/_tmp_anomaly_ro.py b/scripts/_tmp_anomaly_ro.py new file mode 100644 index 0000000..4349d26 --- /dev/null +++ b/scripts/_tmp_anomaly_ro.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +"""Read-only anomaly inventory — no config/switch changes.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(base, path, opener=None, timeout=40): + req = urllib.request.Request(f"{base}{path}", headers={"Content-Type": "application/json"}) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + f"{base}/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=25) + return op + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=60): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n===== {base} =====") + op = login(base) + h = call(base, "/api/health", op) + print("health", { + "yt": (h.get("youtube") or {}).get("ok"), + "yt_err": (h.get("youtube") or {}).get("error"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "pb_err": (h.get("pocketbase") or {}).get("error"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "shorts_run": (h.get("shorts") or {}).get("running"), + "monitor": (h.get("monitor") or {}).get("running"), + }) + try: + pb = call(base, "/api/pb/health", op) + print("pb_health", {k: pb.get(k) for k in ("ok", "in_sync", "max_abs_delta")}) + except Exception as ex: + print("pb_health ERR", ex) + shorts = call(base, "/api/shorts/status", op) + print("shorts_switch_observe_only", shorts.get("enabled"), "running", shorts.get("running"), "err", shorts.get("last_error")) + yt = call(base, "/api/youtube-monitor/status", op) + print("yt_svc", yt.get("youtube_svc")) + live = call(base, "/api/youtube/live-map", op, timeout=90) + print("live", live.get("live_count"), live.get("source")) + +print("\n===== VPS units =====") +v, vr = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print(vr( + "systemctl is-active douyinweb-api douyinweb-yt douyinweb-pb douyinweb-web; " + "/opt/douyinWEB/pb/pocketbase --version 2>/dev/null; " + "curl -sS -m 3 http://127.0.0.1:8092/api/health; echo; " + "curl -sS -m 3 http://127.0.0.1:8020/health; echo; " + "grep -n '_pulse\\|youtube_monitor\\|detail=1' /opt/douyinWEB/backend/app/main.py | head -15; " + "grep -n 'admins/auth\\|_superusers' /opt/douyinWEB/backend/app/pb_sync.py | head -10" +)) +v.close() + +print("\n===== PHYS units =====") +p, pr = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) +print(pr( + "systemctl is-active douyinweb-api douyinweb-yt douyinweb-pb douyinweb-web douyinweb-s3; " + "ls -la /opt/douyinWEB/pb/pocketbase 2>/dev/null; file /opt/douyinWEB/pb/pocketbase 2>/dev/null; " + "/opt/douyinWEB/pb/pocketbase --version 2>/dev/null; " + "systemctl status douyinweb-pb --no-pager -l | head -20; " + "curl -sS -m 3 http://127.0.0.1:8092/api/health 2>&1 | head -c 200; echo; " + "curl -sS -m 3 http://127.0.0.1:8020/health; echo" +)) +p.close() diff --git a/scripts/_tmp_api_stack_restart.py b/scripts/_tmp_api_stack_restart.py new file mode 100644 index 0000000..39c4bae --- /dev/null +++ b/scripts/_tmp_api_stack_restart.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""Stack-sample hung API + connection count; then SIGKILL restart and wait for listen.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=120): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== stop watch ===") +print(sh("systemctl stop douyinweb-api-watch; true")) + +print("=== conn / recvq ===") +print(sh("ss -ltn sport = :8014; ss -tn sport = :8014 | head -5; ss -tn sport = :8014 | wc -l")) + +print("=== try py-spy / pystack ===") +print(sh("pid=$(systemctl show douyinweb-api -p MainPID --value); echo PID=$pid; which py-spy || true; ls /proc/$pid/task | wc -l; timeout 8 py-spy dump --pid $pid 2>/dev/null | head -120 || timeout 5 gdb -batch -p $pid -ex 'thread apply all bt' 2>/dev/null | head -80 || echo no_stack_tool; cat /proc/$pid/wchan; ls -l /proc/$pid/fd | wc -l")) + +print("=== who connects to 8014 top ===") +print(sh("ss -tnp sport = :8014 | awk '{print $5}' | sed 's/:[0-9]*$//' | sort | uniq -c | sort -rn | head -20")) + +print("=== restart clean ===") +print(sh( + "systemctl kill -s SIGKILL douyinweb-api; pkill -9 -f 'uvicorn app.main:app' || true; " + "sleep 2; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api" +)) + +for i in range(36): + time.sleep(5) + code = sh("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo 000").strip() + rq = sh("ss -ltn sport = :8014 | awk 'NR==2{print $2}'").strip() + print(f"[{i}] health={code} recvq={rq}", flush=True) + if code.endswith("200"): + break + +print("=== login after healthy ===") +print(sh(r'''python3 - <<'PY' +import json,urllib.request +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login",data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(),headers={"Content-Type":"application/json"},method="POST") +with urllib.request.urlopen(req,timeout=15) as r: + print("login",r.status,r.read()[:80], (r.headers.get("Set-Cookie") or "")[:120]) +PY''')) + +print("=== leave watch STOPPED ===") +print(sh("systemctl is-active douyinweb-api douyinweb-api-watch; ss -ltn sport = :8014")) +c.close() diff --git a/scripts/_tmp_api_state.py b/scripts/_tmp_api_state.py new file mode 100644 index 0000000..265e7b8 --- /dev/null +++ b/scripts/_tmp_api_state.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""Health/login/watch snapshot for dy + dylive; Recv-Q trend.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def http_get(url, opener=None, timeout=15): + op = opener or urllib.request.build_opener() + try: + with op.open(url, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace")[:200] + except Exception as ex: + return getattr(ex, "code", None), str(ex)[:160] + + +def http_post(url, body, opener=None, timeout=20): + op = opener or urllib.request.build_opener() + req = urllib.request.Request( + url, + data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + try: + with op.open(req, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace")[:160], r.headers.get("Set-Cookie") + except Exception as ex: + return getattr(ex, "code", None), str(ex)[:160], None + + +print("=== public dy ===") +print("health", http_get("https://dy.nomadro.com/api/health")) +print("ping", http_get("https://dy.nomadro.com/api/ping")) +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +st, body, sc = http_post( + "https://dy.nomadro.com/api/auth/login", + {"username": "hackrobot", "password": "Xiao4669805@"}, + opener=op, +) +print("login", st, body, (sc or "")[:100]) +print("status", http_get("https://dy.nomadro.com/api/auth/status", opener=op)) +print("rooms", http_get("https://dy.nomadro.com/api/rooms?limit=1", opener=op)) + +print("=== public dylive ===") +print("health", http_get("https://dylive.nomadro.com/api/health")) +print("ping", http_get("https://dylive.nomadro.com/api/ping")) + +# physical +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=60): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== phys api ===") +print(sh( + "systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-next 2>/dev/null; " + "ss -ltn sport = :8014; " + "ss -tn sport = :8014 | wc -l; " + "curl -sS -m 3 http://127.0.0.1:8014/api/health | head -c 160; echo; " + "journalctl -u douyinweb-api-watch -n 8 --no-pager; " + "journalctl -u douyinweb-api --since '3 min ago' --no-pager | grep -cE 'ingest|ERROR|Traceback' || true" +)) + +# sample Recv-Q for 30s +print("=== recvq sample ===") +for i in range(6): + print(i, sh("ss -ltn sport = :8014 | awk 'NR==2{print $2}'").strip(), flush=True) + time.sleep(5) + +c.close() + +# VPS +c2 = paramiko.SSHClient() +c2.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c2.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def sh2(cmd, t=60): + _, o, e = c2.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== vps api ===") +print(sh2( + "systemctl is-active douyinweb-api douyinweb-api-watch 2>/dev/null; " + "ss -ltn sport = :8014; " + "curl -sS -m 3 http://127.0.0.1:8014/api/health | head -c 160; echo; " + "grep -n 'pure in-process\\|_cn_edge_cache\\|_ping_wg_cache\\|/api/ping' " + "/opt/douyinWEB/backend/app/main.py /opt/douyinWEB/backend/app/youtube_neko.py " + "/opt/douyinWEB/backend/app/network_hub.py /opt/douyinWEB/backend/app/session_auth.py 2>/dev/null | head -20" +)) +c2.close() diff --git a/scripts/_tmp_audit_watches.py b/scripts/_tmp_audit_watches.py new file mode 100644 index 0000000..b521cdc --- /dev/null +++ b/scripts/_tmp_audit_watches.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +"""Read-only: what watchers exist on phys now.""" +from __future__ import annotations + +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" +_, o, e = c.exec_command( + f"echo '{pw}' | sudo -S -p '' bash -lc " + "'systemctl list-unit-files \"douyinweb*\" \"wg-quick@*\" | sed -n \"1,40p\"; " + "echo ---; systemctl is-active douyinweb-api-watch douyinweb-wireguard-watch 2>/dev/null; " + "echo ---; systemctl cat douyinweb-wireguard-watch 2>/dev/null | sed -n \"1,60p\"; " + "echo ---; sed -n \"1,80p\" /opt/douyinWEB/scripts/linux/wireguard_watch.sh 2>/dev/null; " + "echo ---; ls -la /opt/douyinWEB/scripts/linux/'", + timeout=40, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_auth_check.py b/scripts/_tmp_auth_check.py new file mode 100644 index 0000000..4bb56f2 --- /dev/null +++ b/scripts/_tmp_auth_check.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +"""Check physical auth credentials / env without printing secrets.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, sys +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app.settings import settings +from app import session_auth +print("auth_enabled", settings.auth_enabled) +print("admin_user", repr(settings.admin_username)) +pw = str(settings.admin_password or "") +print("admin_pass_len", len(pw), "prefix", pw[:3] if pw else "", "suffix", pw[-2:] if len(pw)>=2 else "") +print("session_secret_len", len(str(settings.session_secret or ""))) +print("secret_prefix", str(settings.session_secret or "")[:8]) + +# try verify common passwords without printing them +cands = [ + "Xiao4669805@", + "Xiao4669805", + "4669805", + "Xiao4669805@!", + os.environ.get("DY_ADMIN_PASSWORD",""), +] +# also from systemd +import subprocess +out = subprocess.getoutput("systemctl show douyinweb-api -p Environment --no-pager") +# parse DY_ADMIN_* +env = {} +for part in out.replace("Environment=","").split(" "): + if "=" in part and part.startswith("DY_"): + k,v = part.split("=",1) + env[k]=v +print("systemd_admin_user", env.get("DY_ADMIN_USERNAME")) +spw = env.get("DY_ADMIN_PASSWORD","") +print("systemd_pass_len", len(spw), "prefix", spw[:3] if spw else "", "suffix", spw[-2:] if len(spw)>=2 else "") +print("settings_matches_systemd_user", settings.admin_username == env.get("DY_ADMIN_USERNAME")) +print("settings_matches_systemd_pass", pw == spw) + +# How login checks +import inspect +from app import main +# find login handler source quickly +import app.session_auth as sa +print("has_verify", hasattr(sa, "verify_password")) +# probe auth users table? +try: + from app import db + print("db_ok") +except Exception as e: + print("db", e) + +# check PB or local users +try: + from app.auth import verify_login + print("verify_login", verify_login) +except Exception as e: + print("no verify_login", e) + +# try login function used by API +import urllib.request, json +for user, password in [("hackrobot", "Xiao4669805@"), ("hackrobot", spw), ("admin", "Xiao4669805@")]: + if not password: continue + req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":user,"password":password}).encode(), headers={"Content-Type":"application/json"}, method="POST") + try: + with urllib.request.urlopen(req, timeout=10) as r: + print("login_ok", user, "pass_len", len(password), r.read()[:80]) + except Exception as e: + code=getattr(e,"code",None) + body="" + try: body=e.read()[:80] + except Exception: pass + print("login_fail", user, "pass_len", len(password), code, body) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_auth_check.py", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_auth_check.py", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_auth_diag.py b/scripts/_tmp_auth_diag.py new file mode 100644 index 0000000..0e8bba2 --- /dev/null +++ b/scripts/_tmp_auth_diag.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +"""Diagnose why dy login rejects hackrobot password.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, sys, json, urllib.request, subprocess +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") + +from app.config import settings +from app.session_auth import verify_admin, verify_session_token, create_session_token, SESSION_COOKIE + +print("auth_enabled", settings.auth_enabled) +print("admin_user", repr(settings.admin_username)) +pw = str(settings.admin_password or "") +print("settings_pass_len", len(pw), "pref", pw[:2] if pw else "", "suf", pw[-2:] if len(pw)>=2 else "") +print("hash?", bool(getattr(settings, "admin_password_hash", None) or "")) + +# systemd env +out = subprocess.getoutput("systemctl show douyinweb-api -p Environment --value") +# Environment can be space-separated KEY=VAL with values containing @ +# Better: systemctl show -p Environment +raw = subprocess.getoutput("systemctl show douyinweb-api -p Environment") +print("env_raw_len", len(raw)) +# parse carefully +vals = {} +# Prefer EnvironmentFile if any +ef = subprocess.getoutput("systemctl show douyinweb-api -p EnvironmentFiles --value") +print("EnvironmentFiles", ef[:200]) +# dump from /proc +pid = subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +print("MainPID", pid) +if pid.isdigit() and int(pid)>1: + try: + with open(f"/proc/{pid}/environ","rb") as f: + env = dict(x.split("=",1) for x in f.read().decode("utf-8","replace").split("\0") if "=" in x) + for k in ["DY_ADMIN_USERNAME","DY_ADMIN_PASSWORD","DY_SESSION_SECRET","DY_AUTH_ENABLED","DY_PUBLIC_BASE_URL"]: + v = env.get(k,"") + if "PASS" in k or "SECRET" in k: + print(k, "len", len(v), "pref", v[:2], "suf", v[-2:] if len(v)>=2 else "") + else: + print(k, repr(v)) + proc_user = env.get("DY_ADMIN_USERNAME","") + proc_pass = env.get("DY_ADMIN_PASSWORD","") + print("verify_admin(proc)", verify_admin(proc_user, proc_pass)) + print("verify_admin(hackrobot, Xiao4669805@)", verify_admin("hackrobot", "Xiao4669805@")) + print("verify_admin(settings)", verify_admin(settings.admin_username, settings.admin_password)) + except Exception as e: + print("proc_env_err", e) + +# HTTP login local +for user, password in [ + ("hackrobot", "Xiao4669805@"), + (settings.admin_username, settings.admin_password), +]: + if not user or not password: + continue + req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":user,"password":password}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=10) as r: + print("http_login_ok", user, r.status, r.read()[:100], "set-cookie", r.headers.get("Set-Cookie","")[:80]) + except Exception as e: + body=b"" + try: body=e.read() + except Exception: pass + print("http_login_fail", user, getattr(e,"code",None), body[:120]) + +# readonly? +try: + from app.authz import verify_readonly + print("readonly_hack", verify_readonly("hackrobot", "Xiao4669805@")) +except Exception as e: + print("readonly_err", e) + +# any .env override +import pathlib +for p in [pathlib.Path(".env"), pathlib.Path("/opt/douyinWEB/backend/.env"), pathlib.Path("/etc/douyinweb.env")]: + if p.is_file(): + print("envfile", p, "size", p.stat().st_size) + txt=p.read_text(encoding="utf-8", errors="ignore") + for line in txt.splitlines(): + if line.startswith("DY_ADMIN_") or line.startswith("DY_AUTH") or line.startswith("DY_SESSION"): + k=line.split("=",1)[0] + v=line.split("=",1)[1] if "=" in line else "" + if "PASS" in k or "SECRET" in k: + print(" ", k, "len", len(v.strip().strip('"').strip("'"))) + else: + print(" ", line[:120]) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_auth_diag.py", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_auth_diag.py", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_auth_fix.py b/scripts/_tmp_auth_fix.py new file mode 100644 index 0000000..c50f2a0 --- /dev/null +++ b/scripts/_tmp_auth_fix.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +"""Compare DB admin hash vs expected; reset to env password if mismatched.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, sys, json, urllib.request +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") +from app.config import settings +from app import db +from app.session_auth import ( + hash_password, get_admin_credentials, verify_admin, + ensure_default_admin_credentials, _secret, +) + +m = db.get_settings_map() +print("db_admin_user", repr(m.get("admin_username"))) +db_hash = str(m.get("admin_password_hash") or "") +print("db_hash_len", len(db_hash), "pref", db_hash[:10]) +exp = hash_password(str(settings.admin_password or "")) +print("expected_len", len(exp), "pref", exp[:10]) +print("match", db_hash == exp) +print("secret_len", len(_secret()), "secret_pref", _secret()[:8]) +u,h = get_admin_credentials() +print("get_admin", repr(u), "hash_pref", h[:10], "eq_expected", h==exp) +print("verify_before", verify_admin("hackrobot", settings.admin_password)) + +# Was ensure ever applied? +print("calling ensure_default_admin_credentials()") +ensure_default_admin_credentials() +m2 = db.get_settings_map() +db_hash2 = str(m2.get("admin_password_hash") or "") +print("after_ensure match", db_hash2 == exp, "changed", db_hash2 != db_hash) +print("verify_after_ensure", verify_admin("hackrobot", settings.admin_password)) + +# Force reset to current env password (operator recovery) +db.update_settings_map({ + "admin_username": str(settings.admin_username or "hackrobot").strip(), + "admin_password_hash": exp, +}) +print("forced_reset verify", verify_admin("hackrobot", "Xiao4669805@")) + +# HTTP login +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=10) as r: + print("login", r.status, r.read()[:120], "cookie", (r.headers.get("Set-Cookie") or "")[:100]) +except Exception as e: + body=b"" + try: body=e.read() + except Exception: pass + print("login_fail", getattr(e,"code",None), body[:160]) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_auth_fix.py", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_auth_fix.py", + timeout=60, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_auth_resync.py b/scripts/_tmp_auth_resync.py new file mode 100644 index 0000000..83ad1b9 --- /dev/null +++ b/scripts/_tmp_auth_resync.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +"""Ensure physical API runs under systemd with correct SESSION_SECRET; verify login.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, sys, json, urllib.request, subprocess, time +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, ".") + +# 1) Show what settings sees vs environ +from app.config import settings +from app.session_auth import _secret, hash_password, ensure_default_admin_credentials, verify_admin +from app import db + +print("settings.session_secret_len", len(str(settings.session_secret or ""))) +print("settings.session_secret_pref", str(settings.session_secret or "")[:8]) +print("_secret_len", len(_secret()), "_secret_pref", _secret()[:8]) +print("env DY_SESSION_SECRET", "set" if os.environ.get("DY_SESSION_SECRET") else "MISSING", "len", len(os.environ.get("DY_SESSION_SECRET") or "")) + +# 2) Force API onto systemd with full env (kill orphans) +subprocess.run("systemctl kill -s SIGKILL douyinweb-api || true", shell=True) +subprocess.run("pkill -9 -f 'uvicorn app.main:app' || true", shell=True) +time.sleep(2) +subprocess.run("systemctl reset-failed douyinweb-api || true", shell=True) +subprocess.run("systemctl start douyinweb-api", shell=True) + +ok=False +for i in range(60): + time.sleep(2) + try: + with urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=4) as r: + if r.status==200: + print("API_UP", i); ok=True; break + except Exception: + pass + if i%5==0: + print("wait", i) +print("api_ok", ok) + +# 3) Re-hash with the LIVE process secret by calling through HTTP after ensure in a one-shot with systemd env +# Run ensure inside a subprocess that loads systemd environment +script = r""" +import os,sys +os.chdir('/opt/douyinWEB/backend'); sys.path.insert(0,'.') +# pull env from running api process +import subprocess +pid=subprocess.getoutput('systemctl show douyinweb-api -p MainPID --value').strip() +env={} +if pid.isdigit() and int(pid)>1: + raw=open(f'/proc/{pid}/environ','rb').read().decode('utf-8','replace').split('\0') + for x in raw: + if '=' in x: + k,v=x.split('=',1); env[k]=v +for k,v in env.items(): + if k.startswith('DY_') or k in ('TZ',): + os.environ[k]=v +from importlib import reload +import app.config as cfg +reload(cfg) +from app.config import settings +from app.session_auth import ensure_default_admin_credentials, verify_admin, hash_password, _secret +from app import db +print('live_secret_len', len(_secret()), 'pref', _secret()[:8]) +print('env_secret_len', len(os.environ.get('DY_SESSION_SECRET') or '')) +ensure_default_admin_credentials() +# force sync hash to current secret+password +exp=hash_password(str(settings.admin_password or '')) +db.update_settings_map({'admin_username': str(settings.admin_username or 'hackrobot'), 'admin_password_hash': exp}) +print('verify', verify_admin('hackrobot', 'Xiao4669805@')) +""" +open('/tmp/_resync_hash.py','w').write(script) +print(subprocess.getoutput('/opt/douyinWEB/backend/.venv/bin/python /tmp/_resync_hash.py')) + +# 4) login test +req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST') +with urllib.request.urlopen(req, timeout=10) as r: + print('local_login', r.status, r.read()[:80], 'set-cookie', (r.headers.get('Set-Cookie') or '')[:90]) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_auth_resync.py", "w") as f: + f.write(REMOTE) +sftp.close() +_, o, e = c.exec_command( + "echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python -u /tmp/_auth_resync.py", + timeout=180, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() + +# public login +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(req, timeout=25) as r: + print("public_login", r.status, r.read()[:120]) +print("cookies", [(x.name, x.domain, x.secure) for x in cj]) +req2 = urllib.request.Request("https://dy.nomadro.com/api/auth/status") +with op.open(req2, timeout=20) as r: + print("public_status", r.read().decode()) diff --git a/scripts/_tmp_auth_up.py b/scripts/_tmp_auth_up.py new file mode 100644 index 0000000..4c268b7 --- /dev/null +++ b/scripts/_tmp_auth_up.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +"""Bring API up; confirm login works publicly.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import subprocess, time, urllib.request, json, os, sys +os.chdir("/opt/douyinWEB/backend") + +def health(): + try: + with urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=3) as r: + return r.status + except Exception: + return 0 + +print("before", health(), flush=True) +if health()!=200: + subprocess.run("systemctl kill -s SIGKILL douyinweb-api || true", shell=True) + subprocess.run("pkill -9 -f 'uvicorn app.main:app' || true", shell=True) + time.sleep(2) + subprocess.run("systemctl reset-failed douyinweb-api || true", shell=True) + subprocess.run("systemctl start douyinweb-api", shell=True) + for i in range(90): + time.sleep(2) + h=health() + if i%5==0: print("wait", i, h, flush=True) + if h==200: + print("UP", i, flush=True); break + else: + print(subprocess.getoutput("journalctl -u douyinweb-api --no-pager -n 30")) + +# ensure hash still correct under live secret +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +print("pid", pid, flush=True) +env={} +if pid.isdigit() and int(pid)>1: + for x in open(f"/proc/{pid}/environ","rb").read().decode("utf-8","replace").split("\0"): + if "=" in x: + k,v=x.split("=",1); env[k]=v +for k,v in env.items(): + if k.startswith("DY_"): + os.environ[k]=v +sys.path.insert(0,".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +exp=hash_password(str(settings.admin_password or "")) +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":exp}) +print("secret_len", len(str(settings.session_secret or "")), "verify", verify_admin("hackrobot","Xiao4669805@"), flush=True) + +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +with urllib.request.urlopen(req, timeout=15) as r: + print("login", r.status, r.read()[:100], flush=True) + print("set-cookie", (r.headers.get("Set-Cookie") or "")[:120], flush=True) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_auth_up.py", "w") as f: + f.write(REMOTE) +sftp.close() +chan = c.get_transport().open_session() +chan.settimeout(15) +chan.exec_command("echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python -u /tmp/_auth_up.py") +deadline = time.time() + 220 +while time.time() < deadline: + if chan.recv_ready(): + print(chan.recv(4096).decode("utf-8", "replace"), end="", flush=True) + if chan.recv_stderr_ready(): + print(chan.recv_stderr(4096).decode("utf-8", "replace"), end="", flush=True) + if chan.exit_status_ready(): + while chan.recv_ready(): + print(chan.recv(4096).decode("utf-8", "replace"), end="", flush=True) + break + time.sleep(0.3) +print("exit", chan.recv_exit_status(), flush=True) +c.close() + +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +try: + with op.open(req, timeout=25) as r: + print("public_login", r.status, r.read()[:150], flush=True) +except Exception as ex: + print("public_login_err", ex, flush=True) + try: + print(ex.read()[:200]) # type: ignore + except Exception: + pass +print("cookies", [(x.name, x.domain, x.secure, x.path) for x in cj], flush=True) +try: + with op.open("https://dy.nomadro.com/api/auth/status", timeout=20) as r: + print("status", r.read().decode(), flush=True) +except Exception as ex: + print("status_err", ex, flush=True) +try: + with op.open("https://dy.nomadro.com/api/rooms?limit=1", timeout=20) as r: + print("rooms", r.status, r.read()[:120], flush=True) +except Exception as ex: + print("rooms_err", getattr(ex, "code", None), ex, flush=True) diff --git a/scripts/_tmp_caddy_neko_ports.py b/scripts/_tmp_caddy_neko_ports.py new file mode 100644 index 0000000..58d27c3 --- /dev/null +++ b/scripts/_tmp_caddy_neko_ports.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def run(cmd): + _, o, e = v.exec_command(cmd, timeout=40) + print((o.read() + e.read()).decode("utf-8", "replace")) + + +run("grep -nE 'reverse_proxy|handle_path /neko|handle_path /ops-neko|1920|920' /etc/caddy/sites/dy.nomadro.com.caddy | sed -n '1,100p'") +run("ls /etc/caddy/sites/") +run("grep -nE 'reverse_proxy|neko|1920|920' /etc/caddy/sites/dy.nomadro.cn.caddy 2>/dev/null | sed -n '1,80p' || echo no_cn_file") +v.close() diff --git a/scripts/_tmp_confirm_login_bounce.py b/scripts/_tmp_confirm_login_bounce.py new file mode 100644 index 0000000..06a9c93 --- /dev/null +++ b/scripts/_tmp_confirm_login_bounce.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +"""Confirm login/rooms; bounce API once for delayed-worker main; keep watch.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +# public check first +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(req, timeout=25) as r: + print("login", r.status, r.read()[:80]) +with op.open("https://dy.nomadro.com/api/auth/status", timeout=15) as r: + print("status", r.read().decode()) +with op.open("https://dy.nomadro.com/api/rooms?limit=1", timeout=20) as r: + print("rooms", r.status, r.read()[:120]) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=120): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("recvq_now", sh("ss -ltn sport = :8014; systemctl is-active douyinweb-api douyinweb-api-watch")) +print("has_delay", sh("grep -n 'Let uvicorn bind' /opt/douyinWEB/backend/app/main.py")) + +# bounce to load delayed workers + keep grace watch +print(sh( + "systemctl stop douyinweb-api-watch; " + "systemctl restart douyinweb-api" +)) +for i in range(24): + time.sleep(5) + code = sh("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + rq = sh("ss -ltn sport = :8014 | awk 'NR==2{print $2}'").strip() + print(f"[{i}] {code} rq={rq}", flush=True) + if code.endswith("200"): + break +print(sh("systemctl start douyinweb-api-watch; sleep 2; systemctl is-active douyinweb-api douyinweb-api-watch; ss -ltn sport = :8014")) +c.close() + +# public again after bounce +time.sleep(2) +cj2 = http.cookiejar.CookieJar() +op2 = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj2)) +with op2.open(req, timeout=25) as r: + print("login2", r.status, r.read()[:80]) +with op2.open("https://dy.nomadro.com/api/auth/status", timeout=15) as r: + print("status2", r.read().decode()) diff --git a/scripts/_tmp_confirm_only.py b/scripts/_tmp_confirm_only.py new file mode 100644 index 0000000..7057f8c --- /dev/null +++ b/scripts/_tmp_confirm_only.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +"""Read-only confirm: dylive ops + shorts/live; dy only observe (do not enable).""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(base, path, opener=None, method="GET", body=None, timeout=45): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n===== {base} =====") + op = login(base) + h = call(base, "/api/health", op) + print("ops_panel_fields", { + "youtube_ok": (h.get("youtube") or {}).get("ok"), + "youtube_monitor_running": (h.get("youtube_monitor") or {}).get("running"), + "pb_ok": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "monitor_running": (h.get("monitor") or {}).get("running"), + }) + shorts = call(base, "/api/shorts/status", op) + print("shorts", { + "enabled": shorts.get("enabled"), + "running": shorts.get("running"), + "busy": shorts.get("busy"), + "quota_gap": shorts.get("quota_gap"), + "processed": shorts.get("processed"), + "sampled": shorts.get("sampled"), + "active_jobs": shorts.get("active_jobs"), + "last_error": shorts.get("last_error"), + }) + ch = call(base, "/api/shorts/channels", op) + rows = ch.get("channels") or [] + print("shorts_channels", len(rows), "enabled", sum(1 for r in rows if r.get("enabled"))) + relay = call(base, "/api/youtube/relay/status", op) + print("relay", { + "enabled": relay.get("enabled"), + "running": relay.get("running"), + "pushing_count": relay.get("pushing_count"), + "enabled_groups": relay.get("enabled_groups"), + "last_error": relay.get("last_error"), + }) + live = call(base, "/api/youtube/live-map", op, timeout=90) + print("live_map", live.get("live_count"), live.get("source")) + try: + pb = call(base, "/api/pb/health", op) + print("pb_health", {"ok": pb.get("ok"), "in_sync": pb.get("in_sync"), "max_abs_delta": pb.get("max_abs_delta")}) + except Exception as ex: + print("pb_health ERR", ex) diff --git a/scripts/_tmp_continue_harden.py b/scripts/_tmp_continue_harden.py new file mode 100644 index 0000000..74f43b5 --- /dev/null +++ b/scripts/_tmp_continue_harden.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +"""Start phys Next; deploy hang/login hardenings to VPS; recheck rooms.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/main.py", + "backend/app/youtube_neko.py", + "backend/app/network_hub.py", + "backend/app/session_auth.py", + "backend/app/shellcrash_hub.py", + "scripts/linux/api_health_watch.sh", +] + + +def public_login_rooms(base: str) -> None: + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + try: + with op.open(req, timeout=25) as r: + print(base, "login", r.status) + except Exception as ex: + print(base, "login ERR", ex) + return + for path in ["/api/auth/status", "/api/rooms?limit=1", "/api/ping", "/api/health"]: + try: + with op.open(f"{base}{path}", timeout=25) as r: + print(base, path, r.status, r.read()[:100]) + except Exception as ex: + print(base, path, "ERR", ex) + + +# --- physical: start next --- +print("=== phys start next ===", flush=True) +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=90): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print(sh("ls /etc/systemd/system/douyinweb*.service 2>/dev/null; systemctl list-unit-files 'douyinweb*' | head -40")) +print(sh( + "systemctl start douyinweb-next 2>/dev/null || systemctl start douyinweb-web 2>/dev/null || true; " + "sleep 2; " + "systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-next douyinweb-web 2>/dev/null; " + "ss -ltn sport = :4015; " + "curl -sS -m 5 -o /dev/null -w 'next:%{http_code}\\n' http://127.0.0.1:4015/ || true" +)) +# local rooms timing +print(sh( + "python3 - <<'PY'\n" + "import json,time,urllib.request,http.cookiejar\n" + "cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\n" + "t0=time.time()\n" + "req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login',data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(),headers={'Content-Type':'application/json'},method='POST')\n" + "print('login',op.open(req,timeout=15).status, round(time.time()-t0,2))\n" + "t0=time.time()\n" + "r=op.open('http://127.0.0.1:8014/api/rooms?limit=1',timeout=30)\n" + "print('rooms',r.status, round(time.time()-t0,2), r.read()[:80])\n" + "PY" +)) +c.close() + +# --- VPS deploy --- +print("=== vps deploy hardenings ===", flush=True) +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = v.open_sftp() +for rel in FILES: + local = ROOT / rel + if not local.is_file(): + print("skip missing", rel) + continue + data = local.read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_dep_{local.name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + dest = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" + _, o, e = v.exec_command(f"install -D -m 644 {tmp} {dest}; wc -c {dest}", timeout=30) + print(rel, (o.read() + e.read()).decode().strip()) +sftp.close() +_, o, e = v.exec_command( + "chmod 755 /opt/douyinWEB/scripts/linux/api_health_watch.sh; " + "bash -n /opt/douyinWEB/scripts/linux/api_health_watch.sh && echo watch_ok; " + "grep -n 'pure in-process\\|_cn_edge_cache\\|/api/ping\\|Let uvicorn bind' " + "/opt/douyinWEB/backend/app/main.py /opt/douyinWEB/backend/app/youtube_neko.py " + "/opt/douyinWEB/backend/app/session_auth.py | head -20; " + "systemctl stop douyinweb-api-watch 2>/dev/null || true; " + "systemctl restart douyinweb-api; " + "sleep 3; systemctl is-active douyinweb-api", + timeout=60, +) +print((o.read() + e.read()).decode()) + +# wait health +for i in range(36): + time.sleep(5) + _, o, e = v.exec_command( + "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo; " + "ss -ltn sport = :8014 | awk 'NR==2{print $2}'", + timeout=20, + ) + out = (o.read() + e.read()).decode().strip() + print(f"vps[{i}] {out}", flush=True) + if out.startswith("200"): + break + +_, o, e = v.exec_command( + "systemctl reset-failed douyinweb-api-watch 2>/dev/null || true; " + "systemctl start douyinweb-api-watch 2>/dev/null || (" + " # create unit if missing" + " test -f /etc/systemd/system/douyinweb-api-watch.service || cat >/etc/systemd/system/douyinweb-api-watch.service <<'EOF'\n" + "[Unit]\nDescription=douyinWEB API health watchdog\nAfter=douyinweb-api.service\n\n" + "[Service]\nType=simple\nExecStart=/bin/bash /opt/douyinWEB/scripts/linux/api_health_watch.sh\n" + "Restart=always\nRestartSec=5\nEnvironment=DY_API_WATCH_START_GRACE=180\nEnvironment=DY_API_WATCH_FAILS=4\n" + "Environment=DY_API_WATCH_COOLDOWN=180\n\n[Install]\nWantedBy=multi-user.target\nEOF\n" + " systemctl daemon-reload; systemctl enable --now douyinweb-api-watch" + "); " + "sleep 2; systemctl is-active douyinweb-api douyinweb-api-watch; " + "curl -sS -m 3 http://127.0.0.1:8014/api/ping; echo", + timeout=40, +) +print((o.read() + e.read()).decode()) +v.close() + +print("=== public recheck ===", flush=True) +public_login_rooms("https://dy.nomadro.com") +public_login_rooms("https://dylive.nomadro.com") diff --git a/scripts/_tmp_deploy_hangfix_login.py b/scripts/_tmp_deploy_hangfix_login.py new file mode 100644 index 0000000..5f04756 --- /dev/null +++ b/scripts/_tmp_deploy_hangfix_login.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +"""Deploy hang fixes; pause Next flood; restart API; verify login.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") +FILES = [ + "backend/app/main.py", + "backend/app/youtube_neko.py", + "backend/app/network_hub.py", + "backend/app/session_auth.py", + "scripts/linux/api_health_watch.sh", +] + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=180): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== units touching 8014 ===") +print(sh( + "systemctl list-units --type=service --all | grep -iE 'douyin|next' | head -40; " + "ss -tnp dport = :8014 2>/dev/null | grep -oP 'users:\\(\\(\"[^\"]+\",pid=\\d+' | sort | uniq -c | sort -rn | head -20" +)) + +print("=== pause next + watch; kill api ===") +print(sh( + "systemctl stop douyinweb-api-watch 2>/dev/null || true; " + "systemctl stop douyinweb-next 2>/dev/null || true; " + "systemctl stop douyinweb-web 2>/dev/null || true; " + "systemctl stop nextjs 2>/dev/null || true; " + "pkill -9 -f 'next-server' 2>/dev/null || true; " + "systemctl kill -s SIGKILL douyinweb-api 2>/dev/null || true; " + "pkill -9 -f 'uvicorn app.main:app' 2>/dev/null || true; " + "sleep 2; " + "ss -tn sport = :8014 | wc -l; " + "systemctl is-active douyinweb-api douyinweb-next 2>/dev/null || true" +)) + +print("=== deploy ===") +sftp = c.open_sftp() +for rel in FILES: + local = ROOT / rel + data = local.read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_dep_{local.name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + dest = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" + print(rel, sh(f"install -D -m 644 {tmp} {dest}; wc -c {dest}").strip()) +sftp.close() +print(sh( + "chmod 755 /opt/douyinWEB/scripts/linux/api_health_watch.sh; " + "grep -n 'pure in-process\\|_cn_edge_cache\\|_ping_wg_cache\\|/api/ping' " + "/opt/douyinWEB/backend/app/main.py /opt/douyinWEB/backend/app/youtube_neko.py " + "/opt/douyinWEB/backend/app/network_hub.py /opt/douyinWEB/backend/app/session_auth.py | head -25" +)) + +print("=== start api only ===") +print(sh("systemctl reset-failed douyinweb-api; systemctl start douyinweb-api")) + +healthy = False +for i in range(48): + time.sleep(5) + code = sh("curl -sS -m 3 -o /tmp/_h.json -w '%{http_code}' http://127.0.0.1:8014/api/health || echo 000").strip() + rq = sh("ss -ltn sport = :8014 | awk 'NR==2{print $2}'").strip() + nconn = sh("ss -tn sport = :8014 | wc -l").strip() + body = sh("tr -d '\\n' /dev/null | head -c 100").strip() + print(f"[{i}] h={code} rq={rq} n={nconn} {body}", flush=True) + if code.endswith("200"): + healthy = True + break + +if not healthy: + print(sh("journalctl -u douyinweb-api -n 40 --no-pager; systemctl status douyinweb-api --no-pager | head -25")) + c.close() + raise SystemExit(2) + +print("=== hash + local login ===") +print(sh(r'''/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import os,sys,json,urllib.request,subprocess +os.chdir("/opt/douyinWEB/backend") +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +for x in open(f"/proc/{pid}/environ","rb").read().decode().split("\0"): + if "=" in x: + k,v=x.split("=",1) + if k.startswith("DY_"): os.environ[k]=v +sys.path.insert(0,".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":hash_password(str(settings.admin_password or ""))}) +print("verify", verify_admin("hackrobot","Xiao4669805@")) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login",data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(),headers={"Content-Type":"application/json"},method="POST") +with urllib.request.urlopen(req,timeout=15) as r: + print("local_login", r.status, (r.headers.get("Set-Cookie") or "")[:150]) +PY''')) + +print("=== start next + watch ===") +print(sh( + "systemctl start douyinweb-next 2>/dev/null || systemctl start douyinweb-web 2>/dev/null || true; " + "systemctl reset-failed douyinweb-api-watch; systemctl start douyinweb-api-watch; " + "sleep 2; systemctl is-active douyinweb-api douyinweb-next douyinweb-api-watch 2>/dev/null; " + "ss -ltn sport = :8014; ss -ltn sport = :4015 | head" +)) +c.close() + +print("=== public login ===") +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +for url in ["https://dy.nomadro.com/api/health", "https://dy.nomadro.com/api/ping"]: + try: + with urllib.request.urlopen(url, timeout=15) as r: + print(url, r.status, r.read()[:100]) + except Exception as ex: + print(url, "ERR", ex) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(req, timeout=25) as r: + print("public_login", r.status, r.read()[:120]) + print("set-cookie", (r.headers.get("Set-Cookie") or "")[:160]) +print("cookies", [(x.name, x.domain) for x in cj]) +with op.open("https://dy.nomadro.com/api/auth/status", timeout=20) as r: + print("status", r.read().decode()) +with op.open("https://dy.nomadro.com/api/rooms?limit=1", timeout=20) as r: + print("rooms", r.status) diff --git a/scripts/_tmp_deploy_watches.py b/scripts/_tmp_deploy_watches.py new file mode 100644 index 0000000..6939072 --- /dev/null +++ b/scripts/_tmp_deploy_watches.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +"""Deploy WG watch fix + Neko health watch to physical host. No business switches.""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + +FILES = [ + ("scripts/linux/wireguard_watch.sh", "/opt/douyinWEB/scripts/linux/wireguard_watch.sh", 0o755), + ("scripts/linux/neko_health_watch.sh", "/opt/douyinWEB/scripts/linux/neko_health_watch.sh", 0o755), + ("scripts/linux/api_health_watch.sh", "/opt/douyinWEB/scripts/linux/api_health_watch.sh", 0o755), +] + +NEKO_UNIT = """[Unit] +Description=douyinWEB Neko HTTP soft-heal watchdog +After=docker.service network-online.target +Wants=network-online.target + +[Service] +Type=simple +Environment=DY_NEKO_WATCH_INTERVAL=30 +Environment=DY_NEKO_WATCH_FAILS=3 +Environment=DY_NEKO_WATCH_COOLDOWN=300 +Environment=DY_NEKO_WATCH_ASSIGN_MAX=8 +Environment=DY_NEKO_WATCH_OPS_MAX=8 +ExecStart=/bin/bash /opt/douyinWEB/scripts/linux/neko_health_watch.sh +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target +""" + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" +sftp = c.open_sftp() +for rel, dest, mode in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_watch_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + _, o, e = c.exec_command( + f"echo '{pw}' | sudo -S -p '' bash -lc {repr(f'install -D -m {mode:o} {tmp} {dest}; ls -la {dest}')}", + timeout=30, + ) + print((o.read() + e.read()).decode()) + +with sftp.file("/tmp/_neko_watch.service", "w") as f: + f.write(NEKO_UNIT.replace("\r\n", "\n")) +sftp.close() + +REMOTE = r''' +set +e +install -m 644 /tmp/_neko_watch.service /etc/systemd/system/douyinweb-neko-watch.service +# Fix WG watch: executable + resilient script already installed; drop empty Environment= that clears vars oddly +mkdir -p /etc/systemd/system/douyinweb-wireguard-watch.service.d +cat > /etc/systemd/system/douyinweb-wireguard-watch.service.d/aggressive.conf <<'EOF' +[Service] +Environment="WIREGUARD_WATCH_IFACES=wg-dy wg-dy-cn" +Environment=WIREGUARD_WATCH_INTERVAL=15 +Environment=WIREGUARD_STALE_SECONDS=90 +Environment=WIREGUARD_RESTART_COOLDOWN=60 +Restart=always +RestartSec=5 +EOF +chmod +x /opt/douyinWEB/scripts/linux/wireguard_watch.sh /opt/douyinWEB/scripts/linux/neko_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh +bash -n /opt/douyinWEB/scripts/linux/wireguard_watch.sh && echo wg_syntax_ok +bash -n /opt/douyinWEB/scripts/linux/neko_health_watch.sh && echo neko_syntax_ok +systemctl daemon-reload +systemctl reset-failed douyinweb-wireguard-watch douyinweb-neko-watch douyinweb-api-watch 2>/dev/null +systemctl enable douyinweb-wireguard-watch douyinweb-neko-watch douyinweb-api-watch +systemctl restart douyinweb-wireguard-watch +systemctl restart douyinweb-neko-watch +systemctl start douyinweb-api-watch +sleep 3 +systemctl is-active douyinweb-wireguard-watch douyinweb-neko-watch douyinweb-api-watch +journalctl -u douyinweb-wireguard-watch -n 8 --no-pager +journalctl -u douyinweb-neko-watch -n 12 --no-pager +# once probe +/opt/douyinWEB/scripts/linux/wireguard_watch.sh once || true +wg show wg-dy-cn | egrep 'handshake|transfer' || true +''' + +sftp = c.open_sftp() +with sftp.file("/tmp/_deploy_watches.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) +sftp.close() +_, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash /tmp/_deploy_watches.sh", timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_diag_api_hang2.py b/scripts/_tmp_diag_api_hang2.py new file mode 100644 index 0000000..ddf8294 --- /dev/null +++ b/scripts/_tmp_diag_api_hang2.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +"""Diagnose physical API hang: Recv-Q, threads, recent journal, ingest rate.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=90): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== stop watch first ===") +print(sh("systemctl stop douyinweb-api-watch; systemctl is-active douyinweb-api-watch || true")) + +print("=== queue / children ===") +print(sh("ss -ltnp | grep 8014; ps --ppid $(systemctl show douyinweb-api -p MainPID --value) -o pid,etime,stat,cmd | head -40; pstree -p $(systemctl show douyinweb-api -p MainPID --value) | head -c 4000")) + +print("=== thread dump-ish ===") +print(sh("pid=$(systemctl show douyinweb-api -p MainPID --value); ls /proc/$pid/task | wc -l; cat /proc/$pid/status | egrep 'State|Threads|VmRSS'")) + +print("=== journal last 2 min access ===") +print(sh("journalctl -u douyinweb-api --since '3 min ago' --no-pager | tail -60")) + +print("=== ingest count last min from journal ===") +print(sh("journalctl -u douyinweb-api --since '5 min ago' --no-pager | grep -c ingest || true; journalctl -u douyinweb-api --since '5 min ago' --no-pager | grep -E 'ingest|ERROR|Traceback|shellcrash|timeout' | tail -40")) + +print("=== deployed debounce marker ===") +print(sh("grep -n 'telemetry.*debounce\\|studio_telemetry\\|write_debounce\\|_TELEMETRY' /opt/douyinWEB/backend/app/youtube_neko.py | head -20; grep -n 'default.*health\\|wait_for' /opt/douyinWEB/backend/app/main.py | head -20")) + +c.close() diff --git a/scripts/_tmp_diag_api_start.py b/scripts/_tmp_diag_api_start.py new file mode 100644 index 0000000..5cba7ea --- /dev/null +++ b/scripts/_tmp_diag_api_start.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +"""Diagnose why physical douyinweb-api won't listen.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=60): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== units ===") +print(sh("systemctl is-active douyinweb-api douyinweb-api-watch; systemctl show douyinweb-api -p ActiveState,SubState,MainPID,NRestarts,ExecMainStatus,Result --no-pager")) +print("=== listen ===") +print(sh("ss -ltnp | grep -E '8014|4015' || true; ps -eo pid,etime,rss,cmd | grep -E 'uvicorn|douyinweb-api' | grep -v grep | head -20")) +print("=== mem ===") +print(sh("free -h; uptime")) +print("=== journal ===") +print(sh("journalctl -u douyinweb-api -n 80 --no-pager")) +print("=== dropins ===") +print(sh("systemctl cat douyinweb-api --no-pager | head -80")) +c.close() diff --git a/scripts/_tmp_diag_phys_neko.py b/scripts/_tmp_diag_phys_neko.py new file mode 100644 index 0000000..7c0a872 --- /dev/null +++ b/scripts/_tmp_diag_phys_neko.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +"""Diagnose why phys dy Neko URLs fail — no config/switch changes.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def http(url, timeout=15, method="GET", body=None, opener=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + url, data=data, method=method, headers={"Content-Type": "application/json", "User-Agent": "curl/8"} + ) + op = opener or urllib.request.build_opener() + try: + with op.open(req, timeout=timeout) as r: + return r.status, r.read()[:200].decode("utf-8", "replace"), dict(r.headers) + except Exception as ex: + return getattr(ex, "code", None), str(ex)[:200], {} + + +print("=== public neko paths ===") +for path in [ + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/2/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", + "https://dy.nomadro.com/ops-neko/1/", +]: + st, body, hdr = http(path, timeout=12) + print(path, st, body[:120].replace("\n", " ")) + +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +http("https://dy.nomadro.com/api/auth/login", method="POST", body={"username": "hackrobot", "password": "Xiao4669805@"}, opener=op) +for path in [ + "/api/youtube/neko/status", + "/api/ops/neko/instances", + "/api/youtube/assign/groups", +]: + st, body, _ = http(f"https://dy.nomadro.com{path}", opener=op, timeout=40) + print(path, st, body[:350].replace("\n", " ")) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=90): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== docker neko ===") +print(sh( + "docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep -E 'neko|NAMES' | head -40; " + "echo ---; ss -ltn | grep -E ':920|:1820|:623' | head -40; " + "echo ---; systemctl is-active docker douyinweb-api nginx caddy 2>/dev/null; " + "ip -br link | grep -E 'wg-dy'; " + "curl -sS -m 3 -o /dev/null -w 'local9200:%{http_code}\\n' http://127.0.0.1:9200/ || true; " + "curl -sS -m 3 -o /dev/null -w 'local9201:%{http_code}\\n' http://127.0.0.1:9201/ || true; " + "curl -sS -m 3 -o /dev/null -w 'ops18200:%{http_code}\\n' http://127.0.0.1:18200/ || true" +)) +print("=== caddy/nginx neko ===") +print(sh( + "grep -n 'neko\\|9200\\|18200' /etc/caddy/Caddyfile 2>/dev/null | head -40; " + "ls /etc/nginx/conf.d/*neko* 2>/dev/null; " + "head -40 /etc/nginx/conf.d/douyinweb-neko-locations.inc 2>/dev/null; " + "journalctl -u docker -n 15 --no-pager 2>/dev/null | tail -15" +)) +c.close() + +# VPS edge for dy.com +print("=== VPS caddy dy neko ===") +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +_, o, e = v.exec_command( + "grep -nE 'neko|18014|9200|19200|18200' /etc/caddy/Caddyfile | head -50; " + "ss -ltn | grep -E ':920|:1920|:1820|:18014' | head; " + "systemctl is-active dy-frp-http-aux frpp 2>/dev/null; " + "curl -sS -m 3 -o /dev/null -w 'vps9200:%{http_code}\\n' http://127.0.0.1:9200/ || true; " + "curl -sS -m 3 -o /dev/null -w 'vps19200:%{http_code}\\n' http://127.0.0.1:19200/ || true", + timeout=40, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +v.close() diff --git a/scripts/_tmp_diag_phys_neko2.py b/scripts/_tmp_diag_phys_neko2.py new file mode 100644 index 0000000..8c086c5 --- /dev/null +++ b/scripts/_tmp_diag_phys_neko2.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +"""Phys Neko deep: containers, chrome, ICE, CN path — no switch changes.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar as cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(url, timeout=20, method="GET", body=None, opener=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + url, data=data, method=method, headers={"Content-Type": "application/json", "User-Agent": "curl/8"} + ) + op = opener or urllib.request.build_opener() + try: + with op.open(req, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace")[:500] + except Exception as ex: + return getattr(ex, "code", None), str(ex)[:200] + + +cj = cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +print("login", call("https://dy.nomadro.com/api/auth/login", method="POST", body={"username": "hackrobot", "password": "Xiao4669805@"}, opener=op)) +for path in ["/api/youtube/neko/status", "/api/ops/neko/peer", "/api/ops/neko/instances"]: + st, body = call(f"https://dy.nomadro.com{path}", opener=op, timeout=45) + print(path, st, body[:400].replace("\n", " ")) + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd, t=120): + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== containers ===") +print(sh( + "docker ps -a --format '{{.Names}}|{{.Status}}' | grep neko | sort; " + "echo ---ports---; " + "for i in 1 2 3 4 5 6 7 8; do " + " code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((9200+i-1))/ 2>/dev/null || echo x); " + " echo assign$i:$code; " + "done; " + "for i in 1 2; do " + " code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((18200+i-1))/ 2>/dev/null || echo x); " + " echo ops$i:$code; " + "done" +)) +print("=== chrome in neko-1/3/ops-1 ===") +print(sh( + "for N in douyinweb-neko-1 douyinweb-neko-3 douyinweb-ops-neko-1; do " + " echo ===== $N =====; " + " docker inspect -f '{{.State.Status}} {{.State.Running}}' $N 2>/dev/null || echo missing; " + " docker exec $N supervisorctl status 2>/dev/null | head -10 || true; " + " docker exec $N sh -c 'ps aux | grep -E chrome|neko | grep -v grep | head -8' 2>/dev/null || true; " + "done" +)) +print("=== wg/cn edge ===") +print(sh( + "ip -br link | grep wg; " + "wg show wg-dy-cn 2>/dev/null | head -15; " + "wg show wg-dy 2>/dev/null | head -10; " + "ping -c1 -W2 10.9.0.1 2>&1 | tail -2; " + "ping -c1 -W2 10.8.0.1 2>&1 | tail -2; " + "curl -sS -m 3 http://127.0.0.1:8014/api/youtube/neko/status 2>/dev/null | head -c 400; echo" +)) +print("=== env nat ===") +print(sh( + "grep -E 'NEKO_NAT|NEKO_CN|PUBLIC_BASE|NEKO_HTTP' /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -30; " + "docker inspect douyinweb-neko-1 --format '{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | grep -iE 'NAT|NEKO_|SCREEN' | head -20" +)) +c.close() + +print("=== public ws-ish ===") +for u in [ + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.com/ops-neko/1/", +]: + print(u, call(u, timeout=10)[0], call(u, timeout=10)[1][:80].replace("\n", " ")) diff --git a/scripts/_tmp_diag_yt_shorts.py b/scripts/_tmp_diag_yt_shorts.py new file mode 100644 index 0000000..14aea30 --- /dev/null +++ b/scripts/_tmp_diag_yt_shorts.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +"""Diagnose YT svc / shorts / live on dylive + dy.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(method, url, body=None, opener=None, timeout=25): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + url, + data=data, + method=method, + headers={"Content-Type": "application/json", "User-Agent": "curl/8"}, + ) + op = opener or urllib.request.build_opener() + try: + with op.open(req, timeout=timeout) as r: + raw = r.read().decode("utf-8", "replace") + return r.status, raw[:800] + except Exception as ex: + return getattr(ex, "code", None), str(ex)[:300] + + +def site(base: str, user="hackrobot", password="Xiao4669805@"): + print(f"\n===== {base} =====") + print("health", call("GET", f"{base}/api/health")) + print("health_detail", call("GET", f"{base}/api/health?detail=1")) + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + print("login", call("POST", f"{base}/api/auth/login", {"username": user, "password": password}, op)) + for path in [ + "/api/youtube-monitor/status", + "/api/shorts/status", + "/api/youtube/relay/status", + "/api/yt-long/status", + "/api/ops/host-metrics", + ]: + st, body = call("GET", f"{base}{path}", opener=op, timeout=40) + print(path, st, body[:350].replace("\n", " ")) + + +def ssh_host(label, host, port, user, password, sudo=False): + print(f"\n===== SSH {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, password, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=90): + if sudo: + cmd = f"echo '{password}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + print(run( + "systemctl is-active douyinweb-api douyinweb-yt douyinweb-web douyinweb-pb douyinweb-s3 2>/dev/null; " + "ss -ltn | grep -E ':8014|:8020|:8092|:8333|:4015' || true" + )) + print("--- yt unit ---") + print(run("systemctl status douyinweb-yt --no-pager -l 2>/dev/null | head -40")) + print("--- yt journal ---") + print(run("journalctl -u douyinweb-yt -n 40 --no-pager 2>/dev/null")) + print("--- curl yt svc ---") + print(run( + "curl -sS -m 5 http://127.0.0.1:8020/health 2>&1 | head -c 300; echo; " + "curl -sS -m 5 http://127.0.0.1:8020/ 2>&1 | head -c 200; echo" + )) + print("--- api health local ---") + print(run("curl -sS -m 8 'http://127.0.0.1:8014/api/health?detail=1' | head -c 600; echo")) + print("--- settings shorts/relay ---") + print(run( + "python3 - <<'PY'\n" + "import sqlite3\n" + "db='/opt/douyinWEB/backend/data/monitor.db'\n" + "con=sqlite3.connect(db)\n" + "keys=('shorts_enabled','youtube_relay_enabled','yt_long_enabled','monitor_enabled')\n" + "for k in keys:\n" + " r=con.execute('select value from settings where key=?',(k,)).fetchone()\n" + " print(k, r[0] if r else None)\n" + "print('shorts_channels', con.execute(\"select count(1) from shorts_channels\").fetchone() if False else 'n/a')\n" + "for t in ('shorts_channels','yt_assign_groups','yt_relay_states'):\n" + " try:\n" + " print(t, con.execute(f'select count(1) from {t}').fetchone()[0])\n" + " except Exception as e:\n" + " print(t, e)\n" + "PY" + )) + print("--- procs ---") + print(run("ps -eo pid,etime,cmd | grep -E 'uvicorn|youtube|node.*8020|yt.svc|douyinweb' | grep -v grep | head -25")) + c.close() + + +site("https://dylive.nomadro.com") +site("https://dy.nomadro.com") +ssh_host("VPS/dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +ssh_host("PHYS/dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) diff --git a/scripts/_tmp_find_caddy_neko.py b/scripts/_tmp_find_caddy_neko.py new file mode 100644 index 0000000..19cde30 --- /dev/null +++ b/scripts/_tmp_find_caddy_neko.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +"""Locate dy.com Neko reverse_proxy targets and align to :1920x if needed.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def vr(cmd, t=90): + _, o, e = v.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print(vr("ls -la /etc/caddy/; wc -l /etc/caddy/Caddyfile; head -5 /etc/caddy/Caddyfile")) +print(vr("rg -n 'dy\\.nomadro|neko|1920|9200|ops-neko' /etc/caddy/ -g '!*.bak' 2>/dev/null | head -80")) +print(vr("caddy adapt --config /etc/caddy/Caddyfile 2>/dev/null | python3 -c \"import sys,json; d=json.load(sys.stdin); print('ok')\" 2>&1 | head")) +# dump site blocks containing neko +print(vr( + "python3 - <<'PY'\n" + "from pathlib import Path\n" + "p=Path('/etc/caddy/Caddyfile')\n" + "text=p.read_text(encoding='utf-8',errors='replace')\n" + "print('len',len(text))\n" + "for key in ['dy.nomadro.com','dy.nomadro.cn','dylive.nomadro.com','/neko','19200','9200','ops-neko']:\n" + " print(key, text.count(key))\n" + "idx=text.find('dy.nomadro.com')\n" + "print('first dy.com idx', idx)\n" + "if idx>=0:\n" + " print(text[idx:idx+2500])\n" + "PY" +)) +v.close() + +# phys with correct sudo +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def pr(cmd, t=90): + # avoid nested quotes issues: write script + return None + + +sftp = p.open_sftp() +script = r'''#!/bin/bash +set +e +wg show wg-dy-cn | egrep 'handshake|transfer' +ping -c1 -W2 10.9.0.1 | tail -2 +for port in 9200 9201 9202 9203 9204 9205 9206 9207 18200 18201; do + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$port/ || echo x) + echo port_$port=$code +done +for N in douyinweb-neko-1 douyinweb-neko-3 douyinweb-ops-neko-1; do + echo ==$N== + docker exec "$N" supervisorctl status 2>/dev/null | head -10 +done +''' +with sftp.file("/tmp/_neko_check.sh", "w") as f: + f.write(script) +sftp.close() +_, o, e = p.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_neko_check.sh", timeout=90) +print("=== PHYS ===") +print((o.read() + e.read()).decode("utf-8", "replace")) +p.close() diff --git a/scripts/_tmp_finish_pb_shorts.py b/scripts/_tmp_finish_pb_shorts.py new file mode 100644 index 0000000..8d8d459 --- /dev/null +++ b/scripts/_tmp_finish_pb_shorts.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +"""Finish PB start, enable dy shorts/relay, verify live+shorts both sites.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ENABLE_PY = r''' +import sqlite3 +con=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +con.execute("create table if not exists kv_settings (key text primary key, value text not null)") +for k,v in [("shorts_enabled","1"),("youtube_relay_enabled","1")]: + con.execute( + "insert into kv_settings(key,value) values(?,?) on conflict(key) do update set value=excluded.value", + (k,v), + ) +con.commit() +rows=con.execute( + "select key,value from kv_settings where key in ('shorts_enabled','youtube_relay_enabled')" +).fetchall() +print("kv", rows) +print("shorts_ch", con.execute("select count(1) from shorts_channels where enabled=1").fetchone()[0]) +print("assign_g", con.execute("select count(1) from yt_assign_groups where enabled=1").fetchone()[0]) +''' + +PB_FIX = r''' +set -e +ls -la /opt/douyinWEB/pb/pocketbase +file /opt/douyinWEB/pb/pocketbase +chmod +x /opt/douyinWEB/pb/pocketbase +# stop crash loop, try foreground once for error +systemctl stop douyinweb-pb || true +sleep 1 +# migrate old windows leftover if any +ls -la /opt/douyinWEB/pb/ | head -20 +# run briefly to see boot error +timeout 4 /opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data 2>&1 | tail -40 || true +# fix unit WorkingDirectory / args if needed +cat >/etc/systemd/system/douyinweb-pb.service <<'EOF' +[Unit] +Description=DouyinWEB PocketBase +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/douyinWEB/pb +ExecStart=/opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl reset-failed douyinweb-pb +systemctl restart douyinweb-pb +sleep 2 +systemctl is-active douyinweb-pb +systemctl status douyinweb-pb --no-pager -l | head -25 +curl -sS -m 3 http://127.0.0.1:8092/api/health || true +echo +''' + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=180): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + def put(local_text: str, remote: str): + sftp = c.open_sftp() + with sftp.file(remote, "w") as f: + f.write(local_text.replace("\r\n", "\n")) + sftp.close() + + return c, run, put + + +def call(base, path, opener=None, method="GET", body=None, timeout=60): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +# ---- VPS ---- +print("===== VPS PB + verify =====", flush=True) +v, vr, vp = ssh("107.173.30.245", 22, "root", "Xiao4669805") +vp(PB_FIX, "/tmp/_pb_fix.sh") +print(vr("bash /tmp/_pb_fix.sh", 60)) +# kick shorts sample if API supports +print(vr( + "curl -sS -m 5 http://127.0.0.1:8020/health; echo; " + "curl -sS -m 5 http://127.0.0.1:8092/api/health; echo; " + "free -h | head -2" +)) +v.close() + +# ---- PHYS ---- +print("===== PHYS PB + enable shorts/relay =====", flush=True) +p, pr, pp = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) +pp(PB_FIX, "/tmp/_pb_fix.sh") +pp(ENABLE_PY, "/tmp/_enable_shorts.py") +print(pr("bash /tmp/_pb_fix.sh", 60)) +print(pr("/opt/douyinWEB/backend/.venv/bin/python /tmp/_enable_shorts.py", 30)) +# reload settings into running API without full restart if possible — restart api to pick kv +print(pr( + "systemctl restart douyinweb-api; sleep 2; " + "systemctl is-active douyinweb-api douyinweb-yt douyinweb-pb douyinweb-s3" +)) +for i in range(24): + time.sleep(5) + code = pr("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + print(f"phys[{i}] {code}", flush=True) + if code.endswith("200"): + break +# force enable via API settings if endpoint exists +p.close() + +print("===== API enable + verify =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n--- {base} ---") + op = login(base) + st, h = call(base, "/api/health", op) + print("health youtube", h.get("youtube"), "pb", h.get("pocketbase"), "s3", h.get("s3"), "ytmon", h.get("youtube_monitor")) + # try settings update endpoints + for path, body in [ + ("/api/settings", {"shorts_enabled": True, "youtube_relay_enabled": True}), + ("/api/shorts/start", {}), + ("/api/youtube/relay/start", {}), + ("/api/youtube-monitor/start", {}), + ]: + try: + st, body_out = call(base, path, op, "POST", body if path == "/api/settings" else None, timeout=30) + print(path, st, str(body_out)[:160]) + except Exception as ex: + # try PUT + try: + if path == "/api/settings": + st, body_out = call(base, path, op, "PUT", body, timeout=30) + print(path, "PUT", st, str(body_out)[:160]) + else: + print(path, "ERR", ex) + except Exception as ex2: + print(path, "ERR", ex2) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "quota_gap", "processed", "sampled", "last_error", "busy")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + ytmon = call(base, "/api/youtube-monitor/status", op)[1] + print("yt_svc", ytmon.get("youtube_svc"), "running", ytmon.get("running")) + try: + live = call(base, "/api/youtube/live-map?force=1", op, timeout=120)[1] + print("live_map", live.get("live_count"), live.get("source"), "entries", len(live.get("entries") or {})) + except Exception as ex: + print("live_map ERR", ex) diff --git a/scripts/_tmp_fix_login_final.py b/scripts/_tmp_fix_login_final.py new file mode 100644 index 0000000..e92bee6 --- /dev/null +++ b/scripts/_tmp_fix_login_final.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +"""Stop watch, start API cleanly, fix login, harden watch grace period.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +WATCH = r'''#!/usr/bin/env bash +set +e +INTERVAL="${DY_API_WATCH_INTERVAL:-20}" +FAILS_NEED="${DY_API_WATCH_FAILS:-4}" +COOLDOWN="${DY_API_WATCH_COOLDOWN:-180}" +GRACE="${DY_API_WATCH_START_GRACE:-180}" +HEALTH_URL="${DY_API_WATCH_URL:-http://127.0.0.1:8014/api/health}" +UNIT="${DY_API_WATCH_UNIT:-douyinweb-api.service}" +log() { printf '[api-watch] %s\n' "$*"; } +fails=0 +last_restart=0 +while true; do + # Grace after unit start — uvicorn often needs >60s before listen + active_enter=$(systemctl show -p ActiveEnterTimestampMonotonic --value "$UNIT" 2>/dev/null) + now_mono=$(cat /proc/uptime 2>/dev/null | awk '{printf "%d", $1*1000000}') + if [ -n "$active_enter" ] && [ "$active_enter" != "0" ] && [ -n "$now_mono" ]; then + # ActiveEnterTimestampMonotonic is usec; /proc/uptime is seconds — compare via systemctl ActiveState age instead + : + fi + age=$(systemctl show -p ActiveEnterTimestamp --value "$UNIT" 2>/dev/null) + # Prefer: if unit is activating/reloading, skip + st=$(systemctl is-active "$UNIT" 2>/dev/null || true) + if [ "$st" != "active" ]; then + log "unit=$st skip" + fails=0 + sleep "$INTERVAL" + continue + fi + # Grace: seconds since ActiveEnterTimestamp + started=$(systemctl show -p ActiveEnterTimestamp --value "$UNIT" 2>/dev/null) + if [ -n "$started" ] && [ "$started" != "n/a" ]; then + start_epoch=$(date -d "$started" +%s 2>/dev/null || echo 0) + now_epoch=$(date +%s) + if [ "$start_epoch" -gt 0 ]; then + up=$((now_epoch - start_epoch)) + if [ "$up" -lt "$GRACE" ]; then + log "grace ${up}/${GRACE}s" + fails=0 + sleep "$INTERVAL" + continue + fi + fi + fi + code=$(curl -sS -m 4 -o /dev/null -w '%{http_code}' "$HEALTH_URL" 2>/dev/null) + [ -n "$code" ] || code=000 + now=$(date +%s) + if [ "$code" = "200" ]; then + fails=0 + else + fails=$((fails + 1)) + log "health=$code fails=$fails/$FAILS_NEED" + fi + if [ "$fails" -ge "$FAILS_NEED" ]; then + elapsed=$((now - last_restart)) + if [ "$elapsed" -ge "$COOLDOWN" ]; then + log "restarting $UNIT" + systemctl kill -s SIGKILL "$UNIT" >/dev/null 2>&1 + pkill -9 -f 'uvicorn app.main:app' >/dev/null 2>&1 + sleep 2 + systemctl reset-failed "$UNIT" >/dev/null 2>&1 + systemctl start "$UNIT" >/dev/null 2>&1 + last_restart=$now + fails=0 + else + log "cooldown ${elapsed}/${COOLDOWN}s" + fi + fi + sleep "$INTERVAL" +done +''' + +REMOTE = r''' +import os, sys, json, time, subprocess, urllib.request +os.chdir("/opt/douyinWEB/backend") + +def run(cmd): + print(subprocess.getoutput(cmd), flush=True) + +print("stop watch", flush=True) +run("systemctl stop douyinweb-api-watch || true") +run("systemctl kill -s SIGKILL douyinweb-api || true") +run("pkill -9 -f 'uvicorn app.main:app' || true") +time.sleep(2) +run("systemctl reset-failed douyinweb-api || true") +run("systemctl start douyinweb-api") + +def health(): + try: + with urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=3) as r: + return r.status + except Exception: + return 0 + +ok=False +for i in range(100): + time.sleep(2) + h=health() + if i%5==0: print("wait", i, h, flush=True) + if h==200: + print("API_OK", i, flush=True); ok=True; break +print("api_ok", ok, flush=True) + +# resync password hash with live secret +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +env={} +if pid.isdigit() and int(pid)>1: + for x in open(f"/proc/{pid}/environ","rb").read().decode("utf-8","replace").split("\0"): + if "=" in x: + k,v=x.split("=",1); env[k]=v +for k,v in env.items(): + if k.startswith("DY_"): + os.environ[k]=v +sys.path.insert(0, ".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +exp=hash_password(str(settings.admin_password or "")) +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":exp}) +print("secret_len", len(str(settings.session_secret or "")), "verify", verify_admin("hackrobot","Xiao4669805@"), flush=True) + +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +with urllib.request.urlopen(req, timeout=15) as r: + print("login", r.status, r.read()[:100], flush=True) + print("cookie", (r.headers.get("Set-Cookie") or "")[:120], flush=True) + +# install new watch script +open("/opt/douyinWEB/scripts/linux/api_health_watch.sh","w").write(open("/tmp/_watch_grace.sh").read()) +os.chmod("/opt/douyinWEB/scripts/linux/api_health_watch.sh", 0o755) +run("systemctl reset-failed douyinweb-api-watch || true") +run("systemctl start douyinweb-api-watch") +time.sleep(2) +run("systemctl is-active douyinweb-api douyinweb-api-watch") +print("DONE", flush=True) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_watch_grace.sh", "w") as f: + f.write(WATCH.replace("\r\n", "\n")) +with sftp.file("/tmp/_fix_login_final.py", "w") as f: + f.write(REMOTE) +sftp.close() +chan = c.get_transport().open_session() +chan.settimeout(20) +chan.exec_command("echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python -u /tmp/_fix_login_final.py") +deadline = time.time() + 250 +while time.time() < deadline: + if chan.recv_ready(): + print(chan.recv(8192).decode("utf-8", "replace"), end="", flush=True) + if chan.recv_stderr_ready(): + print(chan.recv_stderr(8192).decode("utf-8", "replace"), end="", flush=True) + if chan.exit_status_ready(): + while chan.recv_ready(): + print(chan.recv(8192).decode("utf-8", "replace"), end="", flush=True) + break + time.sleep(0.25) +print("\nexit", chan.recv_exit_status(), flush=True) +c.close() + +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(req, timeout=25) as r: + print("public_login", r.status, r.read()[:150], flush=True) +print("cookies", [(x.name, x.domain, x.secure) for x in cj], flush=True) +with op.open("https://dy.nomadro.com/api/auth/status", timeout=20) as r: + print("status", r.read().decode(), flush=True) +with op.open("https://dy.nomadro.com/api/rooms?limit=1", timeout=20) as r: + print("rooms", r.status, flush=True) diff --git a/scripts/_tmp_fix_neko_caddy_ports.py b/scripts/_tmp_fix_neko_caddy_ports.py new file mode 100644 index 0000000..6d9bd68 --- /dev/null +++ b/scripts/_tmp_fix_neko_caddy_ports.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +"""Find where dy.com /neko is proxied; fix FRP/Caddy port mismatch. No switches.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def vr(cmd, t=60): + _, o, e = v.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== Caddy dy neko ===") +print(vr( + "awk '/dy\\.nomadro\\.com|neko|920|1920|1820/{print NR\":\"$0}' /etc/caddy/Caddyfile | head -80; " + "echo '--- blocks ---'; " + "grep -n 'dy.nomadro.com\\|dylive.nomadro.com\\|handle_path /neko\\|reverse_proxy.*92' /etc/caddy/Caddyfile | head -60" +)) +print("=== listeners ===") +print(vr( + "ss -ltn | grep -E ':92|:182|:192' | sort; " + "systemctl status dy-frp-http-aux --no-pager -l | head -35; " + "ps aux | grep -E 'frp|ssh.*920|ssh.*1920' | grep -v grep | head -20" +)) +print("=== curl map ===") +print(vr( + "for p in 9200 9201 19200 19201 18200 18201; do " + " echo -n $p:; curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$p/ || echo x; echo; " + "done" +)) + +# soft neko bounce on phys with proper sudo docker +print("=== phys soft neko + port check ===") +p = paramiko.SSHClient() +p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +p.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" +_, o, e = p.exec_command( + f"echo '{pw}' | sudo -S -p '' bash /dev/stdin <<'EOS'\n" + "set +e\n" + "wg show wg-dy-cn | egrep 'handshake|transfer'\n" + "ping -c1 -W2 10.9.0.1 | tail -2\n" + "for p in 9200 9201 9202 9203 9204 9205 9206 9207 18200 18201; do\n" + " code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$p/ || echo x)\n" + " echo port_$p=$code\n" + "done\n" + "for N in douyinweb-neko-1 douyinweb-neko-2 douyinweb-neko-3 douyinweb-ops-neko-1; do\n" + " echo ==$N==\n" + " docker exec \"$N\" supervisorctl status 2>/dev/null | head -8\n" + "done\n" + "EOS", + timeout=90, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +p.close() +v.close() diff --git a/scripts/_tmp_fix_pb_drift_only.py b/scripts/_tmp_fix_pb_drift_only.py new file mode 100644 index 0000000..4c9668b --- /dev/null +++ b/scripts/_tmp_fix_pb_drift_only.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +"""Fix PB drift on dylive only — sync collections, NO switch/config changes.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(base, path, opener=None, method="GET", body=None, timeout=300): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +base = "https://dylive.nomadro.com" +op = login(base) + +# observe switches before (must stay unchanged) +before = call(base, "/api/shorts/status", op)[1] +relay_before = call(base, "/api/youtube/relay/status", op)[1] +print("BEFORE shorts_enabled", before.get("enabled"), "relay_enabled", relay_before.get("enabled")) + +print("bootstrap", call(base, "/api/pb/bootstrap", op, "POST")[1]) +print("sync-rooms", call(base, "/api/pb/sync-rooms?limit=2000", op, "POST", timeout=300)[1]) +print("sync-groups", call(base, "/api/pb/sync-groups?limit=2000", op, "POST", timeout=120)[1]) +print("sync-sessions", call(base, "/api/pb/sync-sessions?limit=2000", op, "POST", timeout=600)[1]) + +pb = call(base, "/api/pb/health", op)[1] +print("pb_health", { + "ok": pb.get("ok"), + "in_sync": pb.get("in_sync"), + "max_abs_delta": pb.get("max_abs_delta"), + "drift": pb.get("drift"), +}) + +after = call(base, "/api/shorts/status", op)[1] +relay_after = call(base, "/api/youtube/relay/status", op)[1] +print("AFTER shorts_enabled", after.get("enabled"), "relay_enabled", relay_after.get("enabled")) +assert after.get("enabled") == before.get("enabled") +assert relay_after.get("enabled") == relay_before.get("enabled") + +h = call(base, "/api/health", op)[1] +print("ops", { + "yt": (h.get("youtube") or {}).get("ok"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "monitor": (h.get("monitor") or {}).get("running"), +}) +live = call(base, "/api/youtube/live-map", op, timeout=90)[1] +print("live", live.get("live_count"), live.get("source")) + +# dy observe only +base2 = "https://dy.nomadro.com" +op2 = login(base2) +h2 = call(base2, "/api/health", op2)[1] +pb2 = call(base2, "/api/pb/health", op2)[1] +print("\nDY observe", { + "yt": (h2.get("youtube") or {}).get("ok"), + "pb": (h2.get("pocketbase") or {}).get("ok"), + "s3_ok": (h2.get("s3") or {}).get("ok"), + "pb_in_sync": pb2.get("in_sync"), + "shorts_enabled": call(base2, "/api/shorts/status", op2)[1].get("enabled"), + "live": call(base2, "/api/youtube/live-map", op2, timeout=90)[1].get("live_count"), +}) diff --git a/scripts/_tmp_fix_phys_neko_wg.py b/scripts/_tmp_fix_phys_neko_wg.py new file mode 100644 index 0000000..1843969 --- /dev/null +++ b/scripts/_tmp_fix_phys_neko_wg.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +"""Fix phys Neko: restore wg-dy-cn, verify ports/API, soft-refresh NAT if needed. No switch/data changes.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar as cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=120): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +print("===== PHYS =====", flush=True) +p, pr = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) + +print("--- before wg ---", flush=True) +print(pr( + "wg show wg-dy-cn | egrep 'endpoint|handshake|transfer'; " + "wg show wg-dy | egrep 'endpoint|handshake|transfer'; " + "systemctl is-active 'wg-quick@wg-dy-cn' 'wg-quick@wg-dy' douyinweb-api douyinweb-wireguard-watch 2>/dev/null" +)) + +# Refresh CN WG only (Neko ICE depends on it). Do NOT touch sing-box/frpp. +print("--- bounce wg-dy-cn ---", flush=True) +print(pr( + "systemctl restart 'wg-quick@wg-dy-cn'; " + "sleep 3; " + "wg show wg-dy-cn | egrep 'endpoint|latest handshake|transfer'; " + "ping -c 2 -W 2 10.9.0.1 2>&1 | tail -5" +)) + +# Also try overseas wg-dy (FRP fallback path health); if down, restart once +print("--- bounce wg-dy if dead ---", flush=True) +print(pr( + "rx=$(wg show wg-dy transfer 2>/dev/null | awk '{print $2}'); " + "echo wg_dy_rx=$rx; " + "if [ -z \"$rx\" ] || [ \"$rx\" = \"0\" ]; then " + " systemctl restart 'wg-quick@wg-dy'; sleep 3; " + " wg show wg-dy | egrep 'handshake|transfer'; " + " ping -c 1 -W 2 10.8.0.1 2>&1 | tail -2; " + "fi" +)) + +print("--- local neko ports ---", flush=True) +print(pr( + "for p in 9200 9201 9202 9203 9204 9205 9206 9207 18200 18201; do " + " code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$p/ || echo x); " + " echo $p:$code; " + "done; " + "ss -ltn | grep -E ':920|:1820|:5230|:623' | head -30" +)) + +print("--- api health ---", flush=True) +print(pr( + "curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 220; echo; " + "ss -ltn sport = :8014; " + "systemctl is-active douyinweb-api" +)) + +# Soft: if CN still dead after bounce, force VPS NAT on running containers WITHOUT recreate +# by rewriting neko server env file if present and restarting only neko process — prefer CN restore first. +print("--- cn_edge after ---", flush=True) +print(pr( + "python3 - <<'PY'\n" + "import os,time,subprocess\n" + "def hs(iface):\n" + " out=subprocess.getoutput(f'wg show {iface} latest-handshakes')\n" + " print(iface, out)\n" + " try:\n" + " ts=int(out.split()[-1])\n" + " print(' age', int(time.time())-ts if ts else 'none')\n" + " except Exception as e:\n" + " print(' parse', e)\n" + "hs('wg-dy-cn'); hs('wg-dy')\n" + "PY" +)) + +# Soft restart neko server inside containers to pick network — NO chrome profile wipe +# Only restart `neko` supervisord program if exists +print("--- soft neko server bounce (no profile wipe) ---", flush=True) +print(pr( + "for N in $(docker ps --format '{{.Names}}' | grep -E 'douyinweb-(neko|ops-neko)-'); do " + " echo == $N ==; " + " docker exec $N supervisorctl restart neko 2>/dev/null || " + " docker exec $N supervisorctl restart neko-server 2>/dev/null || " + " echo no_neko_svc; " + "done | head -80" +)) +p.close() + +print("===== VPS edge =====", flush=True) +v, vr = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print(vr( + "systemctl is-active dy-frp-http-aux frpp caddy; " + "curl -sS -m 4 -o /dev/null -w 'frp9200:%{http_code}\\n' http://127.0.0.1:9200/; " + "curl -sS -m 4 -o /dev/null -w 'frp19200:%{http_code}\\n' http://127.0.0.1:19200/; " + "curl -sS -m 4 -o /dev/null -w 'frp18200:%{http_code}\\n' http://127.0.0.1:18200/; " + "wg show wg-dy 2>/dev/null | egrep 'handshake|transfer' | head -5; " + "ping -c1 -W2 10.8.0.2 2>&1 | tail -2" +)) +v.close() + +print("===== public ====", flush=True) +for u in [ + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/3/", + "https://dy.nomadro.com/ops-neko/1/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", +]: + try: + with urllib.request.urlopen(u, timeout=15) as r: + print(u, r.status, r.read(60)[:60]) + except Exception as ex: + print(u, "ERR", ex) diff --git a/scripts/_tmp_fix_yt_pb_shorts.py b/scripts/_tmp_fix_yt_pb_shorts.py new file mode 100644 index 0000000..96b7c81 --- /dev/null +++ b/scripts/_tmp_fix_yt_pb_shorts.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +"""Fix PB binary, VPS RAM pressure, enable dy shorts/relay, deploy health+FE, verify.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + +PB_URL = "https://github.com/pocketbase/pocketbase/releases/download/v0.22.34/pocketbase_0.22.34_linux_amd64.zip" + +FILES = [ + ("backend/app/main.py", "/opt/douyinWEB/backend/app/main.py"), + ("frontend/src/app/settings/page.tsx", "/opt/douyinWEB/frontend/src/app/settings/page.tsx"), +] + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=180): + if sudo: + full = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + else: + full = cmd + _, o, e = c.exec_command(full, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +def put_files(c, run, sudo=False): + sftp = c.open_sftp() + for rel, dest in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_dep_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + if sudo: + print(run(f"install -D -m 644 {tmp} {dest}; wc -c {dest}")) + else: + print(run(f"install -D -m 644 {tmp} {dest}; wc -c {dest}")) + sftp.close() + + +def install_pb(run): + print(run( + "set -e; " + "mkdir -p /opt/douyinWEB/pb; " + "if [ -x /opt/douyinWEB/pb/pocketbase ]; then echo PB_EXISTS; /opt/douyinWEB/pb/pocketbase --version || true; exit 0; fi; " + f"cd /tmp; curl -fsSL -o pb.zip '{PB_URL}'; " + "unzip -o pb.zip pocketbase -d /opt/douyinWEB/pb; " + "chmod +x /opt/douyinWEB/pb/pocketbase; " + "/opt/douyinWEB/pb/pocketbase --version; " + "systemctl reset-failed douyinweb-pb; systemctl restart douyinweb-pb; sleep 2; " + "systemctl is-active douyinweb-pb; " + "curl -sS -m 3 http://127.0.0.1:8092/api/health || true" + )) + + +def enable_shorts_relay(run): + # kv_settings + print(run( + "python3 - <<'PY'\n" + "import sqlite3\n" + "con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db')\n" + "con.execute('create table if not exists kv_settings (key text primary key, value text not null)')\n" + "for k,v in [('shorts_enabled','1'),('youtube_relay_enabled','1')]:\n" + " con.execute('insert into kv_settings(key,value) values(?,?) on conflict(key) do update set value=excluded.value',(k,v))\n" + "con.commit()\n" + "rows=con.execute(\"select key,value from kv_settings where key in ('shorts_enabled','youtube_relay_enabled','yt_long_enabled','s3_enabled')\").fetchall()\n" + "print('kv', rows)\n" + "n=con.execute('select count(1) from shorts_channels where enabled=1').fetchone()[0]\n" + "print('shorts_enabled_channels', n)\n" + "g=con.execute('select count(1) from yt_assign_groups where enabled=1').fetchone()[0]\n" + "print('assign_enabled_groups', g)\n" + "PY" + )) + + +def call(base, path, opener=None, method="GET", body=None, timeout=45): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +print("===== VPS =====", flush=True) +v, vrun = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print("mem before", vrun("free -h; ps -eo rss,cmd --sort=-rss | head -20")) +# stop crash-loop noise + pause foreign tiktokWEB if present (frees RAM for shorts) +print(vrun( + "systemctl stop douyinweb-pb 2>/dev/null || true; " + "systemctl stop tiktokweb-api 2>/dev/null || true; " + "systemctl stop tiktokWEB-api 2>/dev/null || true; " + "pkill -f '/opt/tiktokWEB/backend' 2>/dev/null || true; " + "docker ps --format '{{.Names}} {{.Status}}' | head -40" +)) +print("mem mid", vrun("free -h")) +install_pb(vrun) +put_files(v, vrun, sudo=False) +# ensure s3 env / seaweed +print(vrun( + "systemctl list-units --all | grep -iE 's3|seaweed|weed' | head; " + "ss -ltn | grep 8333 || true; " + "grep -E 'DY_S3|S3_' /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -30" +)) +enable_shorts_relay(vrun) +print(vrun( + "systemctl restart douyinweb-yt; " + "systemctl restart douyinweb-api; " + # FE: rebuild if next build dir; otherwise restart web to pick tsx via next if source-mounted + "systemctl restart douyinweb-web; " + "sleep 2; systemctl is-active douyinweb-api douyinweb-yt douyinweb-web douyinweb-pb" +)) +for i in range(24): + time.sleep(5) + code = vrun("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + print(f"vps health[{i}] {code}", flush=True) + if code.endswith("200"): + break +print(vrun("curl -sS -m 5 'http://127.0.0.1:8014/api/health' | head -c 500; echo")) +print(vrun("curl -sS -m 5 http://127.0.0.1:8020/health; echo; curl -sS -m 3 http://127.0.0.1:8092/api/health; echo; free -h")) +v.close() + +print("===== PHYS =====", flush=True) +p, prun = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) +install_pb(prun) +put_files(p, prun, sudo=True) +enable_shorts_relay(prun) +print(prun( + "systemctl restart douyinweb-yt; " + "systemctl restart douyinweb-api; " + "systemctl restart douyinweb-web; " + "sleep 2; systemctl is-active douyinweb-api douyinweb-yt douyinweb-web douyinweb-pb douyinweb-s3" +)) +for i in range(30): + time.sleep(5) + code = prun("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + print(f"phys health[{i}] {code}", flush=True) + if code.endswith("200"): + break +print(prun("curl -sS -m 5 'http://127.0.0.1:8014/api/health' | head -c 500; echo; free -h")) +p.close() + +print("===== PUBLIC VERIFY =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n--- {base} ---") + try: + st, h = call(base, "/api/health", timeout=20) + print("health", st, {k: h.get(k) for k in ("ok", "youtube", "pocketbase", "s3", "youtube_monitor", "shorts", "monitor")}) + except Exception as ex: + print("health ERR", ex) + continue + op = login(base) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "quota_gap", "processed", "sampled", "last_error")}) + ch = call(base, "/api/shorts/channels", op)[1] + rows = ch.get("channels") or [] + en = [r for r in rows if r.get("enabled")] + print("channels", len(rows), "enabled", len(en)) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + ytmon = call(base, "/api/youtube-monitor/status", op)[1] + print("yt_svc", ytmon.get("youtube_svc")) + try: + live = call(base, "/api/youtube/live-map", op, timeout=90)[1] + print("live_map", live.get("live_count"), live.get("source")) + except Exception as ex: + print("live_map ERR", ex) diff --git a/scripts/_tmp_hard_restart_login.py b/scripts/_tmp_hard_restart_login.py new file mode 100644 index 0000000..58abff7 --- /dev/null +++ b/scripts/_tmp_hard_restart_login.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +"""Hard free :8014, restart API, wait for pure /api/health.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" + + +def sh(cmd: str, t: int = 120) -> str: + _, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print("=== free port ===", flush=True) +print( + sh( + "systemctl stop douyinweb-api-watch; " + "systemctl stop douyinweb-api; " + "sleep 1; " + "pkill -9 -f 'uvicorn app.main:app' || true; " + "fuser -k 8014/tcp || true; " + "sleep 2; " + "ss -ltn sport = :8014 || echo PORT_FREE; " + "pgrep -af uvicorn || echo no_uvicorn" + ), + flush=True, +) + +print("=== services ===", flush=True) +print(sh("systemctl list-units --type=service --state=running | grep -i douyin || true"), flush=True) +print(sh("grep -n 'pure in-process' /opt/douyinWEB/backend/app/main.py"), flush=True) + +print("=== start api ===", flush=True) +print(sh("systemctl reset-failed douyinweb-api; systemctl start douyinweb-api"), flush=True) + +healthy = False +for i in range(48): + time.sleep(5) + pid = sh("systemctl show douyinweb-api -p MainPID --value").strip() + listen = sh("ss -ltn sport = :8014").strip() + code = sh( + "curl -sS -m 2 -o /tmp/_h.json -w '%{http_code}' http://127.0.0.1:8014/api/health; echo" + ).strip() + body = sh("head -c 80 /tmp/_h.json 2>/dev/null || true").strip() + j = sh("journalctl -u douyinweb-api -n 4 --no-pager").strip() + print(f"[{i}] pid={pid} code={code!r} listen={listen!r} body={body!r}", flush=True) + print(j[-300:], flush=True) + if code.endswith("200"): + healthy = True + break + +if not healthy: + print("NOT_HEALTHY", flush=True) + print(sh("journalctl -u douyinweb-api -n 60 --no-pager"), flush=True) + c.close() + raise SystemExit(2) + +print("=== login ===", flush=True) +print( + sh( + r"""/opt/douyinWEB/backend/.venv/bin/python - <<'PY' +import os,sys,json,urllib.request,subprocess +os.chdir("/opt/douyinWEB/backend") +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +for x in open(f"/proc/{pid}/environ","rb").read().decode().split("\0"): + if "=" in x: + k,v=x.split("=",1) + if k.startswith("DY_"): os.environ[k]=v +sys.path.insert(0,".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":hash_password(str(settings.admin_password or ""))}) +print("verify", verify_admin("hackrobot","Xiao4669805@")) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login",data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(),headers={"Content-Type":"application/json"},method="POST") +with urllib.request.urlopen(req,timeout=15) as r: + print("local_login", r.status, (r.headers.get("Set-Cookie") or "")[:150]) +PY""" + ), + flush=True, +) + +print("=== start watch (leave next as-is) ===", flush=True) +print( + sh( + "systemctl reset-failed douyinweb-api-watch; systemctl start douyinweb-api-watch; " + "sleep 2; systemctl is-active douyinweb-api douyinweb-api-watch" + ), + flush=True, +) +c.close() + +print("=== public ===", flush=True) +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +with urllib.request.urlopen("https://dy.nomadro.com/api/health", timeout=20) as r: + print("health", r.status, r.read()[:100]) +req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +with op.open(req, timeout=25) as r: + print("login", r.status, r.read()[:100], (r.headers.get("Set-Cookie") or "")[:120]) +with op.open("https://dy.nomadro.com/api/auth/status", timeout=20) as r: + print("status", r.read().decode()) diff --git a/scripts/_tmp_login_now.py b/scripts/_tmp_login_now.py new file mode 100644 index 0000000..ed085dd --- /dev/null +++ b/scripts/_tmp_login_now.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +"""Unstick physical API, resync admin hash, verify public login, start grace watch.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST, PORT, USER, PW = "107.173.30.245", 4014, "eric", "4669805" +USER_NAME, USER_PASS = "hackrobot", "Xiao4669805@" + + +def sh(c, cmd: str, t: int = 90) -> str: + _, o, e = c.exec_command(f"echo '{PW}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def public(url: str, method: str = "GET", body=None, opener=None, timeout: int = 25): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + url, + data=data, + method=method, + headers={"Content-Type": "application/json", "User-Agent": "curl/8"}, + ) + op = opener or urllib.request.build_opener() + try: + with op.open(req, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace"), r.headers + except Exception as ex: + return getattr(ex, "code", None), str(ex), None + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, PORT, USER, PW, timeout=40, allow_agent=False, look_for_keys=False) + + print("=== stop watch + unstick api ===", flush=True) + print(sh(c, "systemctl stop douyinweb-api-watch 2>/dev/null; systemctl is-active douyinweb-api-watch || true"), flush=True) + print(sh(c, "ss -ltn sport = :8014; systemctl is-active douyinweb-api"), flush=True) + print( + sh( + c, + "systemctl kill -s SIGKILL douyinweb-api >/dev/null 2>&1; " + "pkill -9 -f 'uvicorn app.main:app' >/dev/null 2>&1; " + "sleep 2; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api", + 60, + ), + flush=True, + ) + + healthy = False + for i in range(40): + time.sleep(5) + code = sh(c, "curl -sS -m 4 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo 000").strip() + print(f"health[{i}] {code}", flush=True) + if code.endswith("200"): + healthy = True + break + + if not healthy: + print("API_NOT_HEALTHY", flush=True) + print(sh(c, "systemctl status douyinweb-api --no-pager -l | head -40; journalctl -u douyinweb-api -n 30 --no-pager"), flush=True) + c.close() + return + + REMOTE = r''' +import os,sys,json,urllib.request,subprocess +os.chdir("/opt/douyinWEB/backend") +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +env={} +for x in open(f"/proc/{pid}/environ","rb").read().decode("utf-8","replace").split("\0"): + if "=" in x: + k,v=x.split("=",1); env[k]=v +for k,v in env.items(): + if k.startswith("DY_"): os.environ[k]=v +sys.path.insert(0,".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +exp=hash_password(str(settings.admin_password or "")) +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":exp}) +print("secret_len", len(str(settings.session_secret or "")), "verify", verify_admin("hackrobot","Xiao4669805@")) +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", +) +with urllib.request.urlopen(req, timeout=20) as r: + print("local_login", r.status, r.read()[:120]) + print("set-cookie", (r.headers.get("Set-Cookie") or "")[:160]) +''' + sftp = c.open_sftp() + with sftp.file("/tmp/_login_fix.py", "w") as f: + f.write(REMOTE) + watch = open( + r"c:\Users\admin\Desktop\douyinWEB\scripts\linux\api_health_watch.sh", + encoding="utf-8", + ).read().replace("\r\n", "\n") + with sftp.file("/tmp/_watch_grace.sh", "w") as f: + f.write(watch) + sftp.close() + + print("=== resync hash + local login ===", flush=True) + print(sh(c, "/opt/douyinWEB/backend/.venv/bin/python -u /tmp/_login_fix.py", 60), flush=True) + + print("=== install + start grace watch ===", flush=True) + print( + sh( + c, + "install -m 755 /tmp/_watch_grace.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh; " + "bash -n /opt/douyinWEB/scripts/linux/api_health_watch.sh && echo watch_syntax_ok; " + "systemctl reset-failed douyinweb-api-watch || true; " + "systemctl start douyinweb-api-watch; " + "sleep 2; " + "systemctl is-active douyinweb-api douyinweb-api-watch; " + "ss -ltn sport = :8014", + 40, + ), + flush=True, + ) + c.close() + + print("=== public login ===", flush=True) + st, body, _ = public("https://dy.nomadro.com/api/health", timeout=20) + print("public_health", st, (body or "")[:120], flush=True) + + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + st, body, hdrs = public( + "https://dy.nomadro.com/api/auth/login", + method="POST", + body={"username": USER_NAME, "password": USER_PASS}, + opener=op, + timeout=25, + ) + print("public_login", st, (body or "")[:200], flush=True) + if hdrs is not None: + sc = hdrs.get("Set-Cookie") if hasattr(hdrs, "get") else None + print("set-cookie", (sc or "")[:160], flush=True) + print("cookies", [(x.name, x.domain, x.secure) for x in cj], flush=True) + st, body, _ = public("https://dy.nomadro.com/api/auth/status", opener=op, timeout=20) + print("status", st, body, flush=True) + st, body, _ = public("https://dy.nomadro.com/api/rooms?limit=1", opener=op, timeout=20) + print("rooms", st, (body or "")[:120], flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_tmp_login_verify_only.py b/scripts/_tmp_login_verify_only.py new file mode 100644 index 0000000..67efa10 --- /dev/null +++ b/scripts/_tmp_login_verify_only.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +"""Verify login on healthy API; install grace watch. Do NOT restart API.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +HOST, PORT, USER, PW = "107.173.30.245", 4014, "eric", "4669805" + + +def sh(c, cmd: str, t: int = 60) -> str: + _, o, e = c.exec_command(f"echo '{PW}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +def main() -> None: + # public quick + for url in [ + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/api/auth/status", + ]: + try: + with urllib.request.urlopen(url, timeout=15) as r: + print(url, r.status, r.read()[:160].decode("utf-8", "replace")) + except Exception as ex: + print(url, "ERR", getattr(ex, "code", None), ex) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, PORT, USER, PW, timeout=40, allow_agent=False, look_for_keys=False) + + print("=== local health / recvq ===") + print(sh(c, "curl -sS -m 5 -w '\\n%{http_code}\\n' http://127.0.0.1:8014/api/health; ss -ltn sport = :8014; systemctl is-active douyinweb-api douyinweb-api-watch")) + + REMOTE = r''' +import os,sys,json,urllib.request,subprocess +os.chdir("/opt/douyinWEB/backend") +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +env={} +for x in open(f"/proc/{pid}/environ","rb").read().decode("utf-8","replace").split("\0"): + if "=" in x: + k,v=x.split("=",1); env[k]=v +for k,v in env.items(): + if k.startswith("DY_"): os.environ[k]=v +sys.path.insert(0,".") +from importlib import reload +import app.config as cfg; reload(cfg) +from app.config import settings +from app.session_auth import hash_password, verify_admin, ensure_default_admin_credentials +from app import db +ensure_default_admin_credentials() +exp=hash_password(str(settings.admin_password or "")) +db.update_settings_map({"admin_username":"hackrobot","admin_password_hash":exp}) +print("secret_len", len(str(settings.session_secret or "")), "verify", verify_admin("hackrobot","Xiao4669805@")) +req=urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", +) +with urllib.request.urlopen(req, timeout=20) as r: + print("local_login", r.status, r.read()[:120]) + print("set-cookie", (r.headers.get("Set-Cookie") or "")[:180]) +''' + sftp = c.open_sftp() + with sftp.file("/tmp/_login_fix2.py", "w") as f: + f.write(REMOTE) + watch = open( + r"c:\Users\admin\Desktop\douyinWEB\scripts\linux\api_health_watch.sh", + encoding="utf-8", + ).read().replace("\r\n", "\n") + with sftp.file("/tmp/_watch_grace.sh", "w") as f: + f.write(watch) + sftp.close() + + print("=== resync + local login ===") + print(sh(c, "/opt/douyinWEB/backend/.venv/bin/python -u /tmp/_login_fix2.py", 45)) + + print("=== install grace watch ===") + print( + sh( + c, + "install -m 755 /tmp/_watch_grace.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh; " + "bash -n /opt/douyinWEB/scripts/linux/api_health_watch.sh && echo watch_syntax_ok; " + "grep -n START_GRACE /opt/douyinWEB/scripts/linux/api_health_watch.sh | head; " + "systemctl reset-failed douyinweb-api-watch || true; " + "systemctl start douyinweb-api-watch; sleep 2; " + "systemctl is-active douyinweb-api douyinweb-api-watch; " + "journalctl -u douyinweb-api-watch -n 5 --no-pager", + 40, + ) + ) + c.close() + + print("=== public login flow ===") + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + req = urllib.request.Request( + "https://dy.nomadro.com/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with op.open(req, timeout=25) as r: + print("public_login", r.status, r.read()[:200]) + print("set-cookie", (r.headers.get("Set-Cookie") or "")[:180]) + print("cookies", [(x.name, x.domain, x.secure, x.path) for x in cj]) + with op.open("https://dy.nomadro.com/api/auth/status", timeout=20) as r: + print("status", r.read().decode()) + with op.open("https://dy.nomadro.com/api/rooms?limit=1", timeout=20) as r: + print("rooms", r.status, r.read()[:100]) + + +if __name__ == "__main__": + main() diff --git a/scripts/_tmp_neko_soft_unhealthy.py b/scripts/_tmp_neko_soft_unhealthy.py new file mode 100644 index 0000000..d42437c --- /dev/null +++ b/scripts/_tmp_neko_soft_unhealthy.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""Soft-restart unhealthy phys nekos; verify CN + public URLs. No switch/data changes.""" +from __future__ import annotations + +import sys +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +FIX = r'''#!/bin/bash +set +e +echo "=== wg-dy-cn ===" +wg show wg-dy-cn | egrep 'handshake|transfer|endpoint' +ping -c1 -W2 10.9.0.1 | tail -2 + +# soft restart only broken HTTP ports / unhealthy +for id in 3 6 4 7; do + N=douyinweb-neko-$id + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((9200+id-1))/ || echo x) + echo "$N http=$code" + if [ "$code" != "200" ] && [ "$code" != "401" ]; then + echo "soft restart $N chrome+neko" + docker exec "$N" supervisorctl restart neko google-chrome 2>/dev/null || \ + docker exec "$N" supervisorctl restart neko 2>/dev/null + sleep 2 + docker exec "$N" supervisorctl status 2>/dev/null | head -8 + code2=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((9200+id-1))/ || echo x) + echo "$N after=$code2" + fi +done + +echo "=== all assign ports ===" +for id in 1 2 3 4 5 6 7 8; do + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((9200+id-1))/ || echo x) + echo neko$id=$code +done +echo "=== ops ===" +for id in 1 2; do + code=$(curl -sS -m 2 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((18200+id-1))/ || echo x) + echo ops$id=$code +done + +# ensure watch is active for CN +systemctl is-active douyinweb-wireguard-watch || systemctl start douyinweb-wireguard-watch +systemctl is-active douyinweb-wireguard-watch +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_neko_soft.sh", "w") as f: + f.write(FIX) +sftp.close() +_, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_neko_soft.sh", timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() + +print("=== public ===") +for u in [ + "https://dy.nomadro.com/neko/1/", + "https://dy.nomadro.com/neko/3/", + "https://dy.nomadro.com/neko/6/", + "https://dy.nomadro.com/ops-neko/1/", + "https://dy.nomadro.cn/neko/1/", + "https://dy.nomadro.cn/ops-neko/1/", +]: + try: + with urllib.request.urlopen(u, timeout=12) as r: + print(u, r.status) + except Exception as ex: + print(u, "ERR", ex) diff --git a/scripts/_tmp_pb_admin_bootstrap.py b/scripts/_tmp_pb_admin_bootstrap.py new file mode 100644 index 0000000..8cb1ee8 --- /dev/null +++ b/scripts/_tmp_pb_admin_bootstrap.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +"""Create PB admin, re-bootstrap, explain dy relay pushing=0.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=120): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +def call(base, path, opener=None, method="GET", body=None, timeout=60): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +ADMIN_SH = r''' +set +e +cd /opt/douyinWEB/pb +./pocketbase --help 2>&1 | head -40 +echo '---' +# 0.22.x uses: ./pocketbase admin create EMAIL PASS +./pocketbase admin create "hackrobot@dy.nomadro.com" "Xiao4669805@" --dir=./pb_data 2>&1 +./pocketbase admin update "hackrobot@dy.nomadro.com" "Xiao4669805@" --dir=./pb_data 2>&1 +# also try env emails from systemd +EMAIL=$(grep -h DY_PB_ADMIN_EMAIL /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -1 | sed 's/.*=//') +PASS=$(grep -h DY_PB_ADMIN_PASSWORD /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -1 | sed 's/.*=//') +echo "env_email=$EMAIL" +if [ -n "$EMAIL" ] && [ -n "$PASS" ]; then + ./pocketbase admin create "$EMAIL" "$PASS" --dir=./pb_data 2>&1 + ./pocketbase admin update "$EMAIL" "$PASS" --dir=./pb_data 2>&1 +fi +systemctl restart douyinweb-pb +sleep 2 +systemctl is-active douyinweb-pb +curl -sS -m 3 http://127.0.0.1:8092/api/health; echo +''' + +for label, host, port, user, pw, sudo in [ + ("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False), + ("PHYS", "107.173.30.245", 4014, "eric", "4669805", True), +]: + print(f"===== {label} admin =====", flush=True) + c, run = ssh(host, port, user, pw, sudo) + sftp = c.open_sftp() + with sftp.file("/tmp/_pb_admin.sh", "w") as f: + f.write(ADMIN_SH.replace("\r\n", "\n")) + sftp.close() + print(run("bash /tmp/_pb_admin.sh", 60)) + c.close() + +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n===== {base} =====") + op = login(base) + print("bootstrap", call(base, "/api/pb/bootstrap", op, "POST", timeout=120)[1]) + print("pb_health", str(call(base, "/api/pb/health", op)[1])[:400]) + st, h = call(base, "/api/health", op) + print("ops", { + "youtube": h.get("youtube"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "monitor": h.get("monitor"), + }) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "busy", "quota_gap", "processed", "sampled", "active_jobs", "quota_filled", "last_error")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + # dig relay groups why not pushing on dy + try: + st, groups = call(base, "/api/youtube/relay/groups", op, timeout=40) + rows = groups.get("groups") or groups.get("items") or groups + if isinstance(rows, list): + for g in rows[:12]: + if not isinstance(g, dict): + continue + print( + " g", + (g.get("name") or g.get("id") or "")[:28], + "en", + g.get("enabled"), + "st", + (g.get("relay") or g.get("state") or {}).get("status") if isinstance(g.get("relay") or g.get("state"), dict) else g.get("status"), + "prefer", + g.get("neko_open_prefer"), + ) + except Exception as ex: + print("groups ERR", ex) + live = call(base, "/api/youtube/live-map", op, timeout=90)[1] + print("live_map", live.get("live_count"), live.get("source")) diff --git a/scripts/_tmp_pb_auth_fix.py b/scripts/_tmp_pb_auth_fix.py new file mode 100644 index 0000000..e3ae2ed --- /dev/null +++ b/scripts/_tmp_pb_auth_fix.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +"""Test PB admin auth with API env credentials; sync collections.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import os, json, urllib.request, subprocess +# load from api process env +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +env={} +for x in open(f"/proc/{pid}/environ","rb").read().decode("utf-8","replace").split("\0"): + if "=" in x: + k,v=x.split("=",1); env[k]=v +email=env.get("DY_PB_ADMIN_EMAIL") or "hackrobot@douyin.local" +password=env.get("DY_PB_ADMIN_PASSWORD") or "Xiao4669805@" +pb=env.get("DY_PB_URL") or "http://127.0.0.1:8092" +print("pb", pb, "email", email, "pass_len", len(password)) +for path in [ + "/api/admins/auth-with-password", + "/api/collections/_superusers/auth-with-password", +]: + req=urllib.request.Request( + pb+path, + data=json.dumps({"identity":email,"password":password}).encode(), + headers={"Content-Type":"application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=10) as r: + body=r.read().decode()[:200] + print(path, r.status, body) + except Exception as e: + print(path, "ERR", getattr(e,"code",None), e) +# also try create collections via python app +os.chdir("/opt/douyinWEB/backend") +for k,v in env.items(): + if k.startswith("DY_"): os.environ[k]=v +import sys +sys.path.insert(0,".") +import asyncio +from app import pb_sync +async def main(): + print("ensure", await pb_sync.ensure_collections()) + print("health", await pb_sync.health()) +asyncio.run(main()) +''' + +for label, host, port, user, pw, sudo in [ + ("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False), + ("PHYS", "107.173.30.245", 4014, "eric", "4669805", True), +]: + print(f"===== {label} =====", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_pb_auth.py", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + cmd = "/opt/douyinWEB/backend/.venv/bin/python -u /tmp/_pb_auth.py" + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' {cmd}" + _, o, e = c.exec_command(cmd, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() diff --git a/scripts/_tmp_pb_backfill_events.py b/scripts/_tmp_pb_backfill_events.py new file mode 100644 index 0000000..7c983fa --- /dev/null +++ b/scripts/_tmp_pb_backfill_events.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +"""Backfill PB sessions/events/blacklist on dylive — no switch changes.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import asyncio, os, sys +os.chdir("/opt/douyinWEB/backend") +# load systemd env from api +import subprocess +pid=subprocess.getoutput("systemctl show douyinweb-api -p MainPID --value").strip() +for x in open(f"/proc/{pid}/environ","rb").read().decode().split("\0"): + if "=" in x: + k,v=x.split("=",1) + if k.startswith("DY_"): + os.environ[k]=v +sys.path.insert(0,".") +from app import db, pb_sync + +async def main(): + await pb_sync.ensure_collections() + # more sessions (offset via repeated list — list_sessions is recent-first; push up to 5000) + rows = (db.list_sessions(limit=5000, offset=0).get("sessions") or []) + ok=fail=0 + for s in rows: + try: + await pb_sync.sync_session(s); ok+=1 + except Exception: + fail+=1 + print("sessions", ok, fail, "attempted", len(rows)) + + # blacklist if helper exists + bl_ok=bl_fail=0 + try: + items = db.list_blacklist(limit=5000, offset=0) if hasattr(db, "list_blacklist") else None + if items is None: + # raw + import sqlite3 + con=sqlite3.connect("data/monitor.db"); con.row_factory=sqlite3.Row + items=[dict(r) for r in con.execute("select * from blacklist").fetchall()] + for b in items or []: + try: + fn=getattr(pb_sync, "sync_blacklist", None) or getattr(pb_sync, "sync_blacklist_entry", None) + if fn: + await fn(b); bl_ok+=1 + else: + # best-effort create in dy_blacklist + pass + except Exception: + bl_fail+=1 + print("blacklist", bl_ok, bl_fail, "n", len(items or [])) + except Exception as e: + print("blacklist_skip", e) + + # recent events only (cap) — historical full dump not required for ops health + ev_ok=ev_fail=0 + events = db.list_events(limit=2000, offset=0) if hasattr(db, "list_events") else [] + # list_events signature may differ + if isinstance(events, dict): + events = events.get("events") or events.get("items") or [] + for e in events or []: + try: + await pb_sync.sync_event(e); ev_ok+=1 + except Exception: + ev_fail+=1 + print("events", ev_ok, ev_fail, "attempted", len(events or [])) + + h = await pb_sync.sync_health() + print("health", {k:h.get(k) for k in ("ok","in_sync","max_abs_delta")}) + print("drift", h.get("drift")) + +asyncio.run(main()) +''' + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_pb_backfill.py", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) +sftp.close() +_, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -u /tmp/_pb_backfill.py", timeout=600) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_tmp_pb_reset_kick.py b/scripts/_tmp_pb_reset_kick.py new file mode 100644 index 0000000..f46c68c --- /dev/null +++ b/scripts/_tmp_pb_reset_kick.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +"""Reset incompatible PB data, bootstrap, kick shorts both hosts.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PB_RESET = r''' +set -e +systemctl stop douyinweb-pb || true +ts=$(date +%Y%m%d%H%M%S) +if [ -d /opt/douyinWEB/pb/pb_data ]; then + mv /opt/douyinWEB/pb/pb_data /opt/douyinWEB/pb/pb_data.bak.$ts +fi +mkdir -p /opt/douyinWEB/pb/pb_data +# drop broken JS migrations that fight binary migrations +if [ -d /opt/douyinWEB/pb/pb_migrations ]; then + mv /opt/douyinWEB/pb/pb_migrations /opt/douyinWEB/pb/pb_migrations.bak.$ts || true +fi +mkdir -p /opt/douyinWEB/pb/pb_migrations +cat >/etc/systemd/system/douyinweb-pb.service <<'EOF' +[Unit] +Description=DouyinWEB PocketBase +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/douyinWEB/pb +ExecStart=/opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl reset-failed douyinweb-pb +systemctl restart douyinweb-pb +sleep 3 +systemctl is-active douyinweb-pb +curl -sS -m 5 http://127.0.0.1:8092/api/health; echo +# create admin if needed (pb first boot) +# use env from api unit if present +''' + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=180): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + def put(text, remote): + sftp = c.open_sftp() + with sftp.file(remote, "w") as f: + f.write(text.replace("\r\n", "\n")) + sftp.close() + + return c, run, put + + +def call(base, path, opener=None, method="GET", body=None, timeout=60): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + raw = r.read().decode() + try: + return r.status, json.loads(raw) + except Exception: + return r.status, raw[:300] + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +for label, host, port, user, pw, sudo in [ + ("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False), + ("PHYS", "107.173.30.245", 4014, "eric", "4669805", True), +]: + print(f"===== {label} PB reset =====", flush=True) + c, run, put = ssh(host, port, user, pw, sudo=sudo) + put(PB_RESET, "/tmp/_pb_reset.sh") + print(run("bash /tmp/_pb_reset.sh", 60)) + # ensure admin exists via pocketbase superuser upsert (0.22+) + print(run( + "/opt/douyinWEB/pb/pocketbase superuser upsert hackrobot@dy.nomadro.com 'Xiao4669805@' " + "--dir=/opt/douyinWEB/pb/pb_data 2>&1 || " + "/opt/douyinWEB/pb/pocketbase admin upsert hackrobot@dy.nomadro.com 'Xiao4669805@' " + "--dir=/opt/douyinWEB/pb/pb_data 2>&1 || true; " + "systemctl restart douyinweb-pb; sleep 2; " + "systemctl is-active douyinweb-pb; curl -sS -m 3 http://127.0.0.1:8092/api/health; echo" + )) + c.close() + +print("===== bootstrap + kick =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n--- {base} ---") + op = login(base) + for path in [ + "/api/pb/bootstrap", + "/api/shorts/start", + "/api/youtube/relay/start", + "/api/youtube-monitor/start", + "/api/shorts/sample-now", + ]: + try: + st, body = call(base, path, op, "POST", timeout=90) + print(path, st, str(body)[:200]) + except Exception as ex: + print(path, "ERR", ex) + st, h = call(base, "/api/health", op) + print("health", { + "yt": h.get("youtube"), + "pb": h.get("pocketbase"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "shorts": h.get("shorts"), + }) + try: + st, pb = call(base, "/api/pb/health", op, timeout=30) + print("pb_health", st, str(pb)[:250]) + except Exception as ex: + print("pb_health ERR", ex) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "busy", "quota_gap", "processed", "sampled", "active_jobs", "last_error")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + live = call(base, "/api/youtube/live-map", op, timeout=90)[1] + print("live_map", live.get("live_count"), live.get("source")) diff --git a/scripts/_tmp_pb_upgrade25.py b/scripts/_tmp_pb_upgrade25.py new file mode 100644 index 0000000..6eb04a9 --- /dev/null +++ b/scripts/_tmp_pb_upgrade25.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +"""Upgrade PB to 0.25.x (matches pb_sync _superusers), bootstrap both hosts.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PB_URL = "https://github.com/pocketbase/pocketbase/releases/download/v0.25.9/pocketbase_0.25.9_linux_amd64.zip" + +UPGRADE = rf''' +set -e +systemctl stop douyinweb-pb || true +cd /tmp +curl -fsSL -o pb.zip "{PB_URL}" +unzip -o pb.zip pocketbase -d /opt/douyinWEB/pb +chmod +x /opt/douyinWEB/pb/pocketbase +/opt/douyinWEB/pb/pocketbase --version +# fresh data already; recreate superuser for API env email +EMAIL=$(grep -h '^Environment=DY_PB_ADMIN_EMAIL=' /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -1 | cut -d= -f3) +PASS=$(grep -h '^Environment=DY_PB_ADMIN_PASSWORD=' /etc/systemd/system/douyinweb-api.service /etc/systemd/system/douyinweb-api.service.d/* 2>/dev/null | head -1 | cut -d= -f3) +EMAIL=${{EMAIL:-hackrobot@douyin.local}} +PASS=${{PASS:-Xiao4669805@}} +echo "admin $EMAIL" +/opt/douyinWEB/pb/pocketbase superuser upsert "$EMAIL" "$PASS" --dir=/opt/douyinWEB/pb/pb_data +# also common aliases +/opt/douyinWEB/pb/pocketbase superuser upsert "hackrobot@dy.nomadro.com" "$PASS" --dir=/opt/douyinWEB/pb/pb_data || true +/opt/douyinWEB/pb/pocketbase superuser upsert "hackrobot@douyin.local" "$PASS" --dir=/opt/douyinWEB/pb/pb_data || true +cat >/etc/systemd/system/douyinweb-pb.service <<'EOF' +[Unit] +Description=DouyinWEB PocketBase +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/douyinWEB/pb +ExecStart=/opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl reset-failed douyinweb-pb +systemctl restart douyinweb-pb +sleep 2 +systemctl is-active douyinweb-pb +curl -sS -m 3 http://127.0.0.1:8092/api/health; echo +''' + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=180): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + def put(text, remote): + sftp = c.open_sftp() + with sftp.file(remote, "w") as f: + f.write(text.replace("\r\n", "\n")) + sftp.close() + + return c, run, put + + +def call(base, path, opener=None, method="GET", body=None, timeout=90): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +for label, host, port, user, pw, sudo in [ + ("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False), + ("PHYS", "107.173.30.245", 4014, "eric", "4669805", True), +]: + print(f"===== {label} upgrade PB =====", flush=True) + c, run, put = ssh(host, port, user, pw, sudo) + put(UPGRADE, "/tmp/_pb_up.sh") + print(run("bash /tmp/_pb_up.sh", 120)) + c.close() + +print("===== bootstrap =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + op = login(base) + print(base, "bootstrap", call(base, "/api/pb/bootstrap", op, "POST", timeout=180)[1]) + pb = call(base, "/api/pb/health", op)[1] + print(base, "pb_ok", pb.get("ok"), "in_sync", pb.get("in_sync"), "max", pb.get("max_abs_delta")) + h = call(base, "/api/health", op)[1] + print(base, "ops", { + "yt": (h.get("youtube") or {}).get("ok"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "shorts_run": (h.get("shorts") or {}).get("running"), + }) + shorts = call(base, "/api/shorts/status", op)[1] + print(base, "shorts", {k: shorts.get(k) for k in ("enabled", "running", "busy", "quota_gap", "processed", "sampled", "active_jobs", "quota_filled")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print(base, "relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups")}) + live = call(base, "/api/youtube/live-map", op, timeout=90)[1] + print(base, "live", live.get("live_count"), live.get("source")) diff --git a/scripts/_tmp_phys_pb25_finish.py b/scripts/_tmp_phys_pb25_finish.py new file mode 100644 index 0000000..c7fe1db --- /dev/null +++ b/scripts/_tmp_phys_pb25_finish.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +"""Finish phys PB 0.25 upgrade via VPS copy; deploy pb_sync; verify both.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + + def run(cmd, t=180): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +# 1) From VPS, push pocketbase binary to phys via FRP SSH if possible, else re-download on phys +print("===== copy PB binary VPS -> prepare =====", flush=True) +v, vr = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print(vr("ls -la /opt/douyinWEB/pb/pocketbase; /opt/douyinWEB/pb/pocketbase --version")) +# serve file briefly via python http on loopback then phys pulls via? easier: phys curl again with retries +v.close() + +print("===== PHYS install PB 0.25 =====", flush=True) +p, pr = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) +# upload local if we download here, OR retry curl on phys +print(pr( + "set -e; " + "systemctl stop douyinweb-pb || true; " + "cd /tmp; " + "rm -f pb.zip; " + "for i in 1 2 3 4 5; do " + " curl -fL --retry 5 --retry-delay 2 -o pb.zip " + " https://github.com/pocketbase/pocketbase/releases/download/v0.25.9/pocketbase_0.25.9_linux_amd64.zip && break; " + " echo retry_$i; sleep 3; " + "done; " + "ls -la pb.zip; " + "unzip -o pb.zip pocketbase -d /opt/douyinWEB/pb; " + "chmod +x /opt/douyinWEB/pb/pocketbase; " + "/opt/douyinWEB/pb/pocketbase --version; " + # wipe old 0.22 data schema issues if mixed + "rm -rf /opt/douyinWEB/pb/pb_data; mkdir -p /opt/douyinWEB/pb/pb_data; " + "EMAIL=$(grep -h '^Environment=DY_PB_ADMIN_EMAIL=' /etc/systemd/system/douyinweb-api.service | head -1 | cut -d= -f3); " + "PASS=$(grep -h '^Environment=DY_PB_ADMIN_PASSWORD=' /etc/systemd/system/douyinweb-api.service | head -1 | cut -d= -f3); " + "EMAIL=${EMAIL:-hackrobot@dy.nomadro.com}; PASS=${PASS:-Xiao4669805@}; " + "echo admin=$EMAIL; " + "/opt/douyinWEB/pb/pocketbase superuser upsert \"$EMAIL\" \"$PASS\" --dir=/opt/douyinWEB/pb/pb_data; " + "cat >/etc/systemd/system/douyinweb-pb.service <<'EOF'\n" + "[Unit]\nDescription=DouyinWEB PocketBase\nAfter=network.target\n\n" + "[Service]\nType=simple\nWorkingDirectory=/opt/douyinWEB/pb\n" + "ExecStart=/opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data\n" + "Restart=always\nRestartSec=3\nLimitNOFILE=65535\n\n" + "[Install]\nWantedBy=multi-user.target\n" + "EOF\n" + "systemctl daemon-reload; systemctl reset-failed douyinweb-pb; systemctl restart douyinweb-pb; " + "sleep 2; systemctl is-active douyinweb-pb; curl -sS -m 3 http://127.0.0.1:8092/api/health; echo" +, 180)) + +# deploy pb_sync.py +data = (ROOT / "backend/app/pb_sync.py").read_bytes().replace(b"\r\n", b"\n") +sftp = p.open_sftp() +with sftp.file("/tmp/_pb_sync.py", "wb") as f: + f.write(data) +sftp.close() +print(pr("install -m 644 /tmp/_pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py; systemctl restart douyinweb-api")) +for i in range(24): + time.sleep(5) + code = pr("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + print(f"phys api[{i}] {code}", flush=True) + if code.endswith("200"): + break +p.close() + +# also deploy pb_sync to VPS +print("===== VPS deploy pb_sync =====", flush=True) +v, vr = ssh("107.173.30.245", 22, "root", "Xiao4669805") +sftp = v.open_sftp() +with sftp.file("/tmp/_pb_sync.py", "wb") as f: + f.write(data) +sftp.close() +print(vr("install -m 644 /tmp/_pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py; systemctl restart douyinweb-api")) +for i in range(20): + time.sleep(5) + code = vr("curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo").strip() + print(f"vps api[{i}] {code}", flush=True) + if code.endswith("200"): + break +v.close() + + +def call(base, path, opener=None, method="GET", body=None, timeout=120): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +print("===== final verify =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n--- {base} ---") + op = login(base) + try: + print("bootstrap", call(base, "/api/pb/bootstrap", op, "POST", timeout=180)[1]) + except Exception as ex: + print("bootstrap ERR", ex) + try: + pb = call(base, "/api/pb/health", op)[1] + print("pb", pb.get("ok"), "in_sync", pb.get("in_sync"), "max_delta", pb.get("max_abs_delta")) + except Exception as ex: + print("pb ERR", ex) + h = call(base, "/api/health", op)[1] + print("health", { + "yt": (h.get("youtube") or {}).get("ok"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "shorts": h.get("shorts"), + "monitor": h.get("monitor"), + }) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "busy", "quota_gap", "processed", "sampled", "active_jobs", "quota_filled", "last_error")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + live = call(base, "/api/youtube/live-map", op, timeout=90)[1] + print("live", live.get("live_count"), live.get("source")) + # kick shorts once more + try: + call(base, "/api/shorts/sample-now", op, "POST", timeout=60) + except Exception: + pass diff --git a/scripts/_tmp_phys_pb_copy.py b/scripts/_tmp_phys_pb_copy.py new file mode 100644 index 0000000..8ba62b1 --- /dev/null +++ b/scripts/_tmp_phys_pb_copy.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +"""Copy PB 0.25 binary VPS->PHYS via local; fix shorts; verify live.""" +from __future__ import annotations + +import json +import sys +import time +import tempfile +import http.cookiejar +import urllib.request +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PHYS_SH = r''' +set -e +systemctl stop douyinweb-pb || true +install -m 755 /tmp/pocketbase /opt/douyinWEB/pb/pocketbase +/opt/douyinWEB/pb/pocketbase --version +rm -rf /opt/douyinWEB/pb/pb_data +mkdir -p /opt/douyinWEB/pb/pb_data +/opt/douyinWEB/pb/pocketbase superuser upsert "hackrobot@dy.nomadro.com" "Xiao4669805@" --dir=/opt/douyinWEB/pb/pb_data +cat > /etc/systemd/system/douyinweb-pb.service << 'EOF' +[Unit] +Description=DouyinWEB PocketBase +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/douyinWEB/pb +ExecStart=/opt/douyinWEB/pb/pocketbase serve --http=127.0.0.1:8092 --dir=/opt/douyinWEB/pb/pb_data +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target +EOF +systemctl daemon-reload +systemctl reset-failed douyinweb-pb +systemctl restart douyinweb-pb +sleep 2 +systemctl is-active douyinweb-pb +curl -sS -m 3 http://127.0.0.1:8092/api/health +echo +''' + + +def ssh(host, port, user, pw): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + return c + + +print("===== fetch binary from VPS =====", flush=True) +v = ssh("107.173.30.245", 22, "root", "Xiao4669805") +vsftp = v.open_sftp() +local = Path(tempfile.gettempdir()) / "pocketbase_0.25.9" +vsftp.get("/opt/douyinWEB/pb/pocketbase", str(local)) +vsftp.close() +v.close() +print("local size", local.stat().st_size, flush=True) + +print("===== push to PHYS =====", flush=True) +p = ssh("107.173.30.245", 4014, "eric", "4669805") +psftp = p.open_sftp() +psftp.put(str(local), "/tmp/pocketbase") +with psftp.file("/tmp/_pb_phys.sh", "w") as f: + f.write(PHYS_SH.replace("\r\n", "\n")) +# also pb_sync +pb_sync = Path(r"c:\Users\admin\Desktop\douyinWEB\backend\app\pb_sync.py").read_bytes().replace(b"\r\n", b"\n") +with psftp.file("/tmp/_pb_sync.py", "wb") as f: + f.write(pb_sync) +psftp.close() +pw = "4669805" + + +def pr(cmd, t=120): + _, o, e = p.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print(pr("bash /tmp/_pb_phys.sh", 60)) +print(pr("install -m 644 /tmp/_pb_sync.py /opt/douyinWEB/backend/app/pb_sync.py")) +p.close() + + +def call(base, path, opener=None, method="GET", body=None, timeout=90): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", data=data, method=method, headers={"Content-Type": "application/json"} + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +print("===== enable + verify =====", flush=True) +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n--- {base} ---") + op = login(base) + for path in ["/api/pb/bootstrap", "/api/shorts/start", "/api/youtube/relay/start", "/api/youtube-monitor/start"]: + try: + st, body = call(base, path, op, "POST", timeout=180) + print(path, st, str(body)[:180]) + except Exception as ex: + print(path, "ERR", ex) + h = call(base, "/api/health", op)[1] + print("health", { + "yt": (h.get("youtube") or {}).get("ok"), + "pb": (h.get("pocketbase") or {}).get("ok"), + "s3": h.get("s3"), + "ytmon": h.get("youtube_monitor"), + "shorts": h.get("shorts"), + }) + try: + pb = call(base, "/api/pb/health", op)[1] + print("pb_health ok", pb.get("ok"), "in_sync", pb.get("in_sync"), "delta", pb.get("max_abs_delta")) + except Exception as ex: + print("pb_health ERR", ex) + shorts = call(base, "/api/shorts/status", op)[1] + print("shorts", {k: shorts.get(k) for k in ("enabled", "running", "busy", "quota_gap", "processed", "sampled", "active_jobs", "quota_filled", "last_error")}) + relay = call(base, "/api/youtube/relay/status", op)[1] + print("relay", {k: relay.get(k) for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error")}) + live = call(base, "/api/youtube/live-map?force=1", op, timeout=120)[1] + print("live", live.get("live_count"), live.get("source"), "entries", len(live.get("entries") or {})) diff --git a/scripts/_tmp_probe_dy_login.py b/scripts/_tmp_probe_dy_login.py new file mode 100644 index 0000000..ebb52a8 --- /dev/null +++ b/scripts/_tmp_probe_dy_login.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +import json +import sys +import http.cookiejar +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + + +def call(method, url, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + url, + data=data, + method=method, + headers={"Content-Type": "application/json", "User-Agent": "curl/8"}, + ) + try: + with op.open(req, timeout=25) as r: + raw = r.read().decode("utf-8", "replace") + print(method, url, r.status) + print(" headers set-cookie:", r.headers.get_all("Set-Cookie") if hasattr(r.headers, "get_all") else r.headers.get("Set-Cookie")) + print(" body", raw[:300]) + return r.status, raw + except Exception as ex: + print(method, url, "ERR", getattr(ex, "code", None), ex) + try: + print(" body", ex.read()[:300]) # type: ignore + except Exception: + pass + return 0, "" + + +print("=== cookies before ===", list(cj)) +call("GET", "https://dy.nomadro.com/api/auth/status") +call("POST", "https://dy.nomadro.com/api/auth/login", {"username": "hackrobot", "password": "Xiao4669805@"}) +print("=== cookies after login ===") +for c in cj: + print(f" {c.name} domain={c.domain} path={c.path} secure={c.secure} expires={c.expires}") +call("GET", "https://dy.nomadro.com/api/auth/status") +call("GET", "https://dy.nomadro.com/api/rooms?limit=1") +call("GET", "https://dy.nomadro.com/") diff --git a/scripts/_tmp_push_main_only.py b/scripts/_tmp_push_main_only.py new file mode 100644 index 0000000..0f16b94 --- /dev/null +++ b/scripts/_tmp_push_main_only.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import paramiko +from pathlib import Path + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +pw = "4669805" +data = Path(r"c:\Users\admin\Desktop\douyinWEB\backend\app\main.py").read_bytes().replace(b"\r\n", b"\n") +sftp = c.open_sftp() +with sftp.file("/tmp/_main_new.py", "wb") as f: + f.write(data) +sftp.close() +_, o, e = c.exec_command( + f"echo '{pw}' | sudo -S -p '' bash -lc " + "'install -m 644 /tmp/_main_new.py /opt/douyinWEB/backend/app/main.py; " + "grep -n \"Let uvicorn bind\" /opt/douyinWEB/backend/app/main.py | head'", + timeout=30, +) +print((o.read() + e.read()).decode()) +c.close() diff --git a/scripts/_tmp_read_caddy_sites.py b/scripts/_tmp_read_caddy_sites.py new file mode 100644 index 0000000..4c9b4c0 --- /dev/null +++ b/scripts/_tmp_read_caddy_sites.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +"""Read VPS caddy sites for dy neko proxy; fix 9200 vs 19200 mismatch.""" +from __future__ import annotations + +import re +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +v = paramiko.SSHClient() +v.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) + + +def vr(cmd, t=60): + _, o, e = v.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +print(vr("ls -la /etc/caddy/sites/; cat /etc/caddy/Caddyfile")) +print("=== site files with neko/dy ===") +print(vr("grep -RIn -E 'dy\\.nomadro|neko|1920|9200|ops-neko' /etc/caddy/sites/ | head -100")) +print(vr( + "python3 - <<'PY'\n" + "from pathlib import Path\n" + "for p in sorted(Path('/etc/caddy/sites').glob('*')):\n" + " t=p.read_text(encoding='utf-8',errors='replace')\n" + " if 'neko' in t or 'dy.nomadro' in t or '920' in t:\n" + " print('====', p.name, '====')\n" + " print(t[:4000])\n" + " print('----')\n" + "PY" +)) +v.close() diff --git a/scripts/_tmp_restart_neko47.py b/scripts/_tmp_restart_neko47.py new file mode 100644 index 0000000..b86dba2 --- /dev/null +++ b/scripts/_tmp_restart_neko47.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +"""docker restart neko-4/7 only (keep volumes/profiles). No switch changes.""" +from __future__ import annotations + +import sys +import time +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) +sftp = c.open_sftp() +with sftp.file("/tmp/_neko47.sh", "w") as f: + f.write( + """#!/bin/bash +set +e +for id in 4 7; do + N=douyinweb-neko-$id + echo ===== restart $N ===== + docker restart "$N" +done +sleep 8 +for id in 1 2 3 4 5 6 7 8; do + code=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:$((9200+id-1))/ || echo x) + echo neko$id=$code +done +for id in 4 7; do + echo == status neko-$id == + docker exec douyinweb-neko-$id supervisorctl status 2>/dev/null | head -10 +done +wg show wg-dy-cn | egrep 'handshake|transfer' +""" + ) +sftp.close() +_, o, e = c.exec_command("echo '4669805' | sudo -S -p '' bash /tmp/_neko47.sh", timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() + +time.sleep(2) +for u in [ + "https://dy.nomadro.com/neko/4/", + "https://dy.nomadro.com/neko/7/", + "https://dy.nomadro.cn/neko/4/", +]: + try: + with urllib.request.urlopen(u, timeout=15) as r: + print(u, r.status) + except Exception as ex: + print(u, "ERR", ex) diff --git a/scripts/_tmp_yt_deep.py b/scripts/_tmp_yt_deep.py new file mode 100644 index 0000000..0820821 --- /dev/null +++ b/scripts/_tmp_yt_deep.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +"""Deep fix: YT svc health, PB/S3, shorts 9ch both hosts.""" +from __future__ import annotations + +import json +import sys +import time +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def call(base, path, opener=None, method="GET", body=None, timeout=40): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + f"{base}{path}", + data=data, + method=method, + headers={"Content-Type": "application/json"}, + ) + op = opener or urllib.request.build_opener() + with op.open(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def login(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + call(base, "/api/auth/login", op, "POST", {"username": "hackrobot", "password": "Xiao4669805@"}) + return op + + +def ssh(host, port, user, pw, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=120): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + return c, run + + +# Public API truth +for base in ["https://dylive.nomadro.com", "https://dy.nomadro.com"]: + print(f"\n===== API {base} =====") + op = login(base) + ytmon = call(base, "/api/youtube-monitor/status", op) + print("youtube_svc", json.dumps(ytmon.get("youtube_svc"), ensure_ascii=False)[:400]) + print("yt_monitor running", ytmon.get("running"), "enabled", ytmon.get("yt_monitor_enabled")) + shorts = call(base, "/api/shorts/status", op) + print( + "shorts", + { + k: shorts.get(k) + for k in ( + "enabled", + "running", + "quota_gap", + "processed", + "sampled", + "last_error", + "yt_quota", + ) + }, + ) + ch = call(base, "/api/shorts/channels", op) + rows = ch.get("channels") or ch.get("items") or ch + if isinstance(rows, list): + print("shorts_channels", len(rows)) + for r in rows[:12]: + if isinstance(r, dict): + print( + " ", + r.get("id") or r.get("channel_id"), + (r.get("title") or r.get("name") or "")[:40], + "enabled", + r.get("enabled"), + ) + relay = call(base, "/api/youtube/relay/status", op) + print( + "relay", + { + k: relay.get(k) + for k in ("enabled", "running", "pushing_count", "enabled_groups", "last_error") + }, + ) + try: + live = call(base, "/api/youtube/live-map", op, timeout=90) + print("live_map", live.get("live_count"), live.get("source"), "entries", len(live.get("entries") or {})) + except Exception as ex: + print("live_map ERR", ex) + +# VPS deep +print("\n===== VPS fix probe =====") +c, run = ssh("107.173.30.245", 22, "root", "Xiao4669805") +print(run("free -h; uptime; systemctl is-active douyinweb-pb douyinweb-s3 douyinweb-yt douyinweb-api douyinweb-web")) +print(run("systemctl status douyinweb-pb --no-pager -l | head -35")) +print(run("systemctl status douyinweb-s3 --no-pager -l | head -25")) +print(run("curl -sS -m 5 http://127.0.0.1:8020/health; echo; curl -sS -m 5 http://127.0.0.1:8092/api/health 2>&1 | head -c 200; echo")) +print(run("ls -la /opt/douyinWEB/pb/ | head; file /opt/douyinWEB/pb/pocketbase 2>/dev/null; systemctl cat douyinweb-pb | head -40")) +print(run( + "python3 -c \"import sqlite3; c=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db'); " + "print([(k,c.execute('select value from app_settings where key=?',(k,)).fetchone() or c.execute('select value from settings where key=?',(k,)).fetchone()) " + "for k in ['shorts_enabled','youtube_relay_enabled','yt_long_enabled']])\"" +)) +# find settings table +print(run( + "python3 - <<'PY'\n" + "import sqlite3\n" + "con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db')\n" + "print(con.execute(\"select name from sqlite_master where type='table'\").fetchall())\n" + "for t in con.execute(\"select name from sqlite_master where type='table'\").fetchall():\n" + " n=t[0]\n" + " if 'setting' in n.lower() or 'short' in n.lower():\n" + " print('TABLE', n, con.execute(f'pragma table_info({n})').fetchall()[:8])\n" + "PY" +)) +c.close() + +c2, run2 = ssh("107.173.30.245", 4014, "eric", "4669805", sudo=True) +print("\n===== PHYS probe =====") +print(run2("free -h; systemctl is-active douyinweb-pb douyinweb-s3 douyinweb-yt douyinweb-api douyinweb-web")) +print(run2("curl -sS -m 5 http://127.0.0.1:8020/health; echo")) +print(run2("systemctl status douyinweb-pb --no-pager -l | head -30")) +c2.close() diff --git a/scripts/_truth_timeslot_live.py b/scripts/_truth_timeslot_live.py new file mode 100644 index 0000000..c7f11bf --- /dev/null +++ b/scripts/_truth_timeslot_live.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Truth: live list vs probe vs relay for asian streetfood time_slot.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_ts_truth.py", "w") as f: + f.write( + r""" +import json, time, sqlite3, os, sys +sys.path.insert(0, '/opt/douyinWEB/backend') +os.chdir('/opt/douyinWEB/backend') + +from app import db +from app import youtube_relay_pipeline as yrp +from app import yt_assign_db +from app import youtube_relay_db +from app.douyin_live import check_room + +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +g=yt_assign_db.get_group(gid) or {} +print('group', g.get('name'), 'cat', g.get('category'), 'prefer', g.get('neko_open_prefer'), 'ops', g.get('ops_neko_slot')) + +# active slot? +print('in_active_slot', yrp._group_in_active_slot(gid, keyed_only=True)) + +rooms=db.list_live_douyin_rooms_for_shorts(limit=40) +print('LIVE_LIST_COUNT', len(rooms)) +for i,r in enumerate(rooms[:12]): + print(f" [{i}] rid={r.get('room_id')} anchor={r.get('last_anchor') or r.get('last_title')} url={str(r.get('url') or '')[:70]}") + +src=yrp.pick_source_for_group(g, respect_schedule=True) +print('PICK', src) + +st=youtube_relay_db.get_relay_state(gid) or {} +print('RELAY', {k:st.get(k) for k in ('status','error','source_url','source_room_id','anchor_name','ffmpeg_pid','push_seconds')}) +log=st.get('recent_log') or [] +if isinstance(log,str): + try: log=json.loads(log) + except: log=log.splitlines() +print('LOG_TAIL') +for ln in list(log)[-15:]: + print(' ', ln) + +# probe current relay source AND first live list room +cookie='' +try: + cookie=str(db.get_settings_map().get('douyin_cookie') or '') +except Exception: + pass +targets=[] +if st.get('source_url'): + targets.append(('relay_src', st.get('source_url'))) +if src and src.get('source_url'): + targets.append(('pick_src', src.get('source_url'))) +if rooms: + targets.append(('live0', rooms[0].get('url'))) +seen=set() +for name,url in targets: + if not url or url in seen: continue + seen.add(url) + try: + import asyncio + p=asyncio.get_event_loop().run_until_complete(check_room(url, cookie=cookie)) if False else None + except Exception: + p=None + # sync wrapper? + try: + from app import douyin_live + import asyncio + p=asyncio.run(check_room(url, cookie=cookie)) + except Exception as ex: + print('PROBE_FAIL', name, type(ex).__name__, ex) + continue + print('PROBE', name, 'live', getattr(p,'live',None) or (p.get('live') if isinstance(p,dict) else None), 'status', getattr(p,'status',None) or (p.get('status') if isinstance(p,dict) else None), 'risk', getattr(p,'risk',None) if not isinstance(p,dict) else p.get('risk'), 'url', str(url)[:60]) + if isinstance(p, dict): + print(' keys', {k:p.get(k) for k in ('ok','live','status','anchor_name','flv','error') if k in p or True}) +""" + ) + sftp.close() + _, o, e = c.exec_command("cd /opt/douyinWEB/backend && .venv/bin/python /tmp/_ts_truth.py 2>&1 || python3 /tmp/_ts_truth.py 2>&1", timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_truth_timeslot_live2.py b/scripts/_truth_timeslot_live2.py new file mode 100644 index 0000000..1210880 --- /dev/null +++ b/scripts/_truth_timeslot_live2.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +REMOTE = r''' +import json, asyncio, sys +sys.path.insert(0, "/opt/douyinWEB/backend") +from app import db +from app import youtube_relay_pipeline as yrp +from app import yt_assign_db +from app import youtube_relay_db +from app.douyin import check_room + +gid = "3fb8cbf7-2180-45bc-99f0-836169f0bf97" +g = yt_assign_db.get_group(gid) or {} +print("group", g.get("name"), "cat", g.get("category"), "prefer", g.get("neko_open_prefer"), "ops", g.get("ops_neko_slot")) +print("in_active_slot", yrp._group_in_active_slot(gid, keyed_only=True)) + +rooms = db.list_live_douyin_rooms_for_shorts(limit=40) +print("LIVE_LIST_COUNT", len(rooms)) +for i, r in enumerate(rooms[:15]): + print( + f" [{i}] rid={r.get('room_id')} " + f"anchor={(r.get('last_anchor') or r.get('last_title') or '')[:40]} " + f"url={str(r.get('url') or '')[:70]}" + ) + +src = yrp.pick_source_for_group(g, respect_schedule=True) +print("PICK", src) + +st = youtube_relay_db.get_relay_state(gid) or {} +print( + "RELAY", + { + k: st.get(k) + for k in ( + "status", + "error", + "source_url", + "source_room_id", + "anchor_name", + "ffmpeg_pid", + "push_seconds", + ) + }, +) +log = st.get("recent_log") or [] +if isinstance(log, str): + try: + log = json.loads(log) + except Exception: + log = log.splitlines() +print("LOG_TAIL") +for ln in list(log)[-20:]: + print(" ", ln) + +cfg = db.get_settings_map() +cookie = str(cfg.get("dy_cookie") or "").strip() +print("cookie_len", len(cookie)) + +async def probe(url: str): + return await check_room(url, cookie=cookie) + +targets = [] +if st.get("source_url"): + targets.append(("relay_stuck", st.get("source_url"))) +if src and src.get("source_url"): + targets.append(("pick", src.get("source_url"))) +if rooms: + targets.append(("live0", rooms[0].get("url"))) + if len(rooms) > 1: + targets.append(("live1", rooms[1].get("url"))) + +seen = set() +for name, url in targets: + if not url or url in seen: + continue + seen.add(url) + p = asyncio.run(probe(url)) + print( + "PROBE", + name, + "ok", + p.get("ok"), + "live", + p.get("is_live"), + "status", + p.get("status_code"), + "cands", + len(p.get("stream_candidates") or []) if isinstance(p.get("stream_candidates"), list) else 0, + "anchor", + (p.get("anchor_name") or "")[:30], + "url", + str(url)[:55], + ) +''' + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_ts_truth2.py", "w") as f: + f.write(REMOTE) + sftp.close() + _, o, e = c.exec_command( + "/opt/douyinWEB/backend/.venv/bin/python /tmp/_ts_truth2.py", + timeout=120, + ) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_ui_cleanup_unused_busy.py b/scripts/_ui_cleanup_unused_busy.py new file mode 100644 index 0000000..7a1f736 --- /dev/null +++ b/scripts/_ui_cleanup_unused_busy.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +from pathlib import Path +import re + +ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB") + +# yt-long +p = ROOT / "frontend/src/app/yt-long/page.tsx" +t = p.read_text(encoding="utf-8") +t = t.replace(" const [busy, setBusy] = useState(false);\n", "") +t = t.replace("busy={busy}", "busy={false}") +t = re.sub(r"\{false \? ]+/>)\}", r"\1", t) +p.write_text(t, encoding="utf-8") +print("yt-long", "busy state", "[busy, setBusy]" in t) + +# clips +p = ROOT / "frontend/src/app/x/ClipsPanel.tsx" +t = p.read_text(encoding="utf-8") +t = t.replace(" const [busy, setBusy] = useState(false);\n", "") +t = t.replace("busy={busy}", "busy={false}") +p.write_text(t, encoding="utf-8") +print("clips", "busy state", "[busy, setBusy]" in t) + +for rel in ("frontend/src/app/youtube/page.tsx", "desktop/src/pages/YoutubePage.tsx"): + p = ROOT / rel + t = p.read_text(encoding="utf-8") + if "setBusy(" not in t: + t = t.replace(" const [busy, setBusy] = useState(false);\n", "") + t = re.sub(r"\{false \? ]+/>)\}", r"\1", t) + p.write_text(t, encoding="utf-8") + print(rel, "setBusy(", t.count("setBusy("), "state", "[busy, setBusy]" in t) + +print("ok") diff --git a/scripts/_ui_fix_assign_busy.py b/scripts/_ui_fix_assign_busy.py new file mode 100644 index 0000000..24862de --- /dev/null +++ b/scripts/_ui_fix_assign_busy.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +"""Refactor YtAssignPanel busy → per-action pending (UI only).""" +from pathlib import Path +import re + +path = Path(r"c:\Users\admin\Desktop\douyinWEB\frontend\src\components\YtAssignPanel.tsx") +text = path.read_text(encoding="utf-8") + +old_state = " const [busy, setBusy] = useState(false);" +new_state = """ /** Per-action pending — never freeze the whole panel on one toggle. */ + const [pending, setPending] = useState>({}); + const isPending = useCallback((key: string) => Boolean(pending[key]), [pending]); + const withPending = useCallback(async (key: string, fn: () => Promise) => { + setPending((p) => { + if (p[key]) return p; + return { ...p, [key]: true }; + }); + try { + await fn(); + } finally { + setPending((p) => { + const n = { ...p }; + delete n[key]; + return n; + }); + } + }, []);""" +if old_state not in text: + raise SystemExit("state not found") +text = text.replace(old_state, new_state, 1) + +old_load = """ const loadGroups = useCallback(async () => { + setBusy(true); + try { + const [data] = await Promise.all([ + fetchJson("/api/youtube/assign/groups"), + loadSchedule(), + ]); + const list: AssignGroup[] = data.groups || []; + setGroups(list); + setGroupId((prev) => { + if (focusGroupId && list.some((g) => g.id === focusGroupId)) return focusGroupId; + if (prev && list.some((g) => g.id === prev)) return prev; + return list[0]?.id || ""; + }); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(false); + } + }, [toast, loadSchedule, focusGroupId]);""" + +new_load = """ const loadGroups = useCallback(async () => { + try { + const [data] = await Promise.all([ + fetchJson("/api/youtube/assign/groups"), + loadSchedule(), + ]); + const list: AssignGroup[] = data.groups || []; + setGroups(list); + setGroupId((prev) => { + if (focusGroupId && list.some((g) => g.id === focusGroupId)) return focusGroupId; + if (prev && list.some((g) => g.id === prev)) return prev; + return list[0]?.id || ""; + }); + } catch (e) { + toast.push((e as Error).message, "err"); + } + }, [toast, loadSchedule, focusGroupId]);""" +if old_load not in text: + raise SystemExit("loadGroups not found") +text = text.replace(old_load, new_load, 1) + +# Wrap remaining setBusy(true) ... finally setBusy(false) blocks by converting to withPending +# Simpler: replace setBusy(true) with begin via unique auto keys is hard. +# Instead strip setBusy calls and use withPending only for key handlers; remove disabled={busy}. + +# refreshAllAvatars +text2 = text +text2 = text2.replace(" setBusy(true);\n try {\n const r = await fetchJson(\"/api/youtube/manage/profiles/refresh", + " await withPending(\"avatars\", async () => {\n try {\n const r = await fetchJson(\"/api/youtube/manage/profiles/refresh", 1) +# fix avatars finally +old = """ } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(false); + } + }, [loadAllProfiles, toast]);""" +new = """ } catch (e) { + toast.push((e as Error).message, "err"); + } + }); + }, [loadAllProfiles, toast, withPending]);""" +if old not in text2: + # maybe already partially changed + print("avatars block pattern missing, continue") +else: + text2 = text2.replace(old, new, 1) + +# Remove all remaining setBusy(true)/setBusy(false) — actions stay async without global lock +text2 = text2.replace(" setBusy(true);\n", "") +text2 = text2.replace(" setBusy(true);\n", "") +# remove finally { setBusy(false); } blocks that only clear busy +text2 = re.sub( + r"\n(\s*)\} finally \{\n\1 setBusy\(false\);\n\1\}", + r"\n\1}", + text2, +) +text2 = re.sub( + r"\n(\s*)finally \{\n\1 setBusy\(false\);\n\1\}\n", + r"\n", + text2, +) +# leftover setBusy +if "setBusy" in text2: + print("leftover setBusy lines:") + for i, line in enumerate(text2.splitlines(), 1): + if "setBusy" in line or "busy" == line.strip() or "busy," in line: + if "setBusy" in line or "busy={busy}" in line or "disabled={busy}" in line or "Boolean(busy)" in line: + print(i, line.strip()[:120]) + +# Hero busy prop: only avatars pending +text2 = text2.replace(" busy={busy}", ' busy={isPending("avatars")}') + +# disabled={busy} → remove (keep clickable). For create/save use specific pending later. +# disabled={busy || ...} → disabled={...} +text2 = text2.replace(" disabled={busy || ", " disabled={") +text2 = text2.replace("disabled={busy || ", "disabled={") +# plain disabled={busy} remove attribute (leave space cleanup) +text2 = re.sub(r"\s*disabled=\{busy\}", "", text2) + +# time_slot armed / category: add scoped disable + optimistic (manual patch below if needed) +path.write_text(text2, encoding="utf-8") +print("written", path) +print("setBusy left", text2.count("setBusy")) +print("disabled busy left", text2.count("disabled={busy}")) +print("busy={busy} left", text2.count("busy={busy}")) +PY diff --git a/scripts/_ui_fix_desktop_shorts_busy.py b/scripts/_ui_fix_desktop_shorts_busy.py new file mode 100644 index 0000000..ad8a70d --- /dev/null +++ b/scripts/_ui_fix_desktop_shorts_busy.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +"""Desktop ShortsPage: remove global busy disable (UI only).""" +from pathlib import Path +import re + +p = Path(r"c:\Users\admin\Desktop\douyinWEB\desktop\src\pages\ShortsPage.tsx") +t = p.read_text(encoding="utf-8") +# Keep busy for spinners if used, but stop disabling all buttons +t2 = re.sub(r"\s*disabled=\{busy\}", "", t) +t2 = t2.replace("disabled={busy || ", "disabled={") +t2 = t2.replace("disabled={busy||", "disabled={") +# Remove setBusy lock around ops — keep API calls +t2 = t2.replace(" setBusy(true);\n", "") +t2 = t2.replace(" setBusy(true);\n", "") +t2 = t2.replace(" setBusy(true);\n", "") +t2 = re.sub( + r"\n(\s*)\} finally \{\n\1 setBusy\(false\);\n\1\}", + r"\n\1}", + t2, +) +t2 = re.sub(r"\n(\s*)setBusy\(false\);\n", "\n", t2) +# If busy state unused except spinner, leave state — or replace busy ? spinner with false +# Check leftover +p.write_text(t2, encoding="utf-8") +print("disabled busy", t2.count("disabled={busy}")) +print("setBusy", t2.count("setBusy")) +for i, line in enumerate(t2.splitlines(), 1): + if re.search(r"(?>({}); + const isPending = useCallback((key: string) => Boolean(pending[key]), [pending]); + const withPending = useCallback(async (key: string, fn: () => Promise) => { + setPending((p) => (p[key] ? p : { ...p, [key]: true })); + try { + await fn(); + } finally { + setPending((p) => { + const n = { ...p }; + delete n[key]; + return n; + }); + } + }, []);""" +if old not in text: + raise SystemExit("busy state not found") +text = text.replace(old, new, 1) + +# Ensure useCallback imported +if "useCallback" not in text.split("from \"react\"")[0]: + text = text.replace( + "import { useEffect, useMemo, useRef, useState", + "import { useCallback, useEffect, useMemo, useRef, useState", + 1, + ) + text = text.replace( + "import {\n useEffect,\n useMemo,\n useRef,\n useState,", + "import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,", + 1, + ) + +# Remove setBusy(true/false) lines +text = text.replace(" setBusy(true);\n", "") +text = text.replace(" setBusy(true);\n", "") +text = text.replace(" setBusy(true);\n", "") +text = re.sub( + r"\n(\s*)\} finally \{\n\1 setBusy\(false\);\n\1\}", + r"\n\1}", + text, +) +text = re.sub( + r"\n(\s*)finally \{\n\1 setBusy\(false\);\n\1\}\n", + "\n", + text, +) +text = re.sub(r"\n(\s*)setBusy\(false\);\n", "\n", text) + +# disabled={busy || X} -> disabled={X} +text = text.replace("disabled={busy || ", "disabled={") +text = text.replace("disabled={busy||", "disabled={") +# disabled={busy} remove +text = re.sub(r"\s*disabled=\{busy\}", "", text) + +path.write_text(text, encoding="utf-8") +print("setBusy", text.count("setBusy"), "disabled busy", text.count("disabled={busy}")) +# check useCallback import +import_line = [l for l in text.splitlines() if 'from "react"' in l or "from 'react'" in l][:3] +print("react imports:", import_line) +PY diff --git a/scripts/_ui_fix_shorts_busy2.py b/scripts/_ui_fix_shorts_busy2.py new file mode 100644 index 0000000..63de7db --- /dev/null +++ b/scripts/_ui_fix_shorts_busy2.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +from pathlib import Path +import re + +p = Path(r"c:\Users\admin\Desktop\douyinWEB\frontend\src\app\shorts\page.tsx") +t = p.read_text(encoding="utf-8") + +t = t.replace( + "const [pending, setPending] = useState>({});", + "const [actionPending, setActionPending] = useState>({});", + 1, +) +t = t.replace( + "const isPending = useCallback((key: string) => Boolean(pending[key]), [pending]);", + "const isPending = useCallback((key: string) => Boolean(actionPending[key]), [actionPending]);", + 1, +) +old_wp = """ const withPending = useCallback(async (key: string, fn: () => Promise) => { + setPending((p) => (p[key] ? p : { ...p, [key]: true })); + try { + await fn(); + } finally { + setPending((p) => { + const n = { ...p }; + delete n[key]; + return n; + }); + } + }, []);""" +new_wp = """ const withPending = useCallback(async (key: string, fn: () => Promise) => { + setActionPending((p) => (p[key] ? p : { ...p, [key]: true })); + try { + await fn(); + } finally { + setActionPending((p) => { + const n = { ...p }; + delete n[key]; + return n; + }); + } + }, []);""" +if old_wp not in t: + raise SystemExit("withPending block missing") +t = t.replace(old_wp, new_wp, 1) + +t = t.replace('busy={busy}', 'busy={isPending("quota")}') +t = t.replace( + "{busy ? : }", + '{isPending("saveChannel") ? : }', +) + +# Wrap DailyQuota onSave/onApply to mark quota pending? optional — busy prop already isPending quota +# but nothing sets it. Change busy={false} for quota card or wire withPending in callbacks. +t = t.replace('busy={isPending("quota")}', "busy={false}") + +# Find remaining bare `busy` identifiers +print("--- leftover busy ---") +for i, line in enumerate(t.splitlines(), 1): + if "busy" not in line: + continue + if any( + x in line + for x in ( + "uploadBusy", + "status?.busy", + "busy={uploadBusy}", + "busy={togglingId", + "busy={false}", + "busy={isPending", + "· 忙碌", + ) + ): + continue + if re.search(r"(? None: + t = path.read_text(encoding="utf-8") + orig = t + # Remove disabled={busy} and simplify disabled={busy || X} + t = re.sub(r"\s*disabled=\{busy\}", "", t) + t = t.replace("disabled={busy || ", "disabled={") + t = t.replace("disabled={busy||", "disabled={") + # Drop setBusy lock lines (API calls remain) + t = t.replace(" setBusy(true);\n", "") + t = t.replace(" setBusy(true);\n", "") + t = t.replace(" setBusy(true);\n", "") + t = re.sub( + r"\n(\s*)\} finally \{\n\1 setBusy\(false\);\n\1\}", + r"\n\1}", + t, + ) + t = re.sub(r"\n(\s*)setBusy\(false\);\n", "\n", t) + # Spinners referencing busy → always show icon (or false) + t = t.replace("{busy ? 6000 else out, flush=True) + return code, out + + +c = connect() +try: + run(c, "systemctl is-active douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "systemctl restart douyinweb-pb douyinweb-api douyinweb-yt douyinweb-web; sleep 4; " + "systemctl is-active douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; " + "uptime; free -h | head -2") + run(c, "curl -sS -m 20 http://127.0.0.1:8014/api/health | head -c 400; echo; " + "curl -sS -m 20 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "timeout 15 docker ps --format '{{.Names}} {{.Status}}' 2>/dev/null | head -20 || echo docker_slow") +finally: + c.close() +print("DONE", flush=True) diff --git a/scripts/_verify_assign_tm_now.py b/scripts/_verify_assign_tm_now.py new file mode 100644 index 0000000..04bdf75 --- /dev/null +++ b/scripts/_verify_assign_tm_now.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +INNER = r''' +import json, os, re, urllib.request, time +from pathlib import Path +ext="dhdgffkkebhmkfjojejmpbldmpobfkfo" +# wait cdp +tabs=[] +for _ in range(12): + try: + tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3).read()) + break + except Exception: + time.sleep(2) +pref=Path("/home/neko/.config/google-chrome/Default/Preferences") +e={} +if pref.exists(): + e=((json.loads(pref.read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {} +print("tm", e.get("state"), e.get("location"), e.get("from_webstore")) +print("ext", Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0/manifest.json").exists()) +les=Path(f"/home/neko/.config/google-chrome/Default/Local Extension Settings/{ext}") +print("les_dir", les.is_dir(), "files", len(list(les.glob("*"))) if les.is_dir() else 0) +sp=Path("/home/neko/.config/google-chrome/Default/Secure Preferences") +print("secure_bytes", sp.stat().st_size if sp.exists() else -1) +found=False +for pid in os.listdir("/proc"): + if not pid.isdigit(): continue + try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00",b" ").decode() + except Exception: continue + if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd: + m=re.search(r"--load-extension=([^ ]+)", cmd) + print("load_ext", m.group(1) if m else None); found=True; break +if not found: print("load_ext NONE") +print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or ""))) +print("tab_n", len(tabs)) +''' + +REMOTE = r''' +NAMES=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort) +echo "running: $NAMES" +for name in $NAMES; do + echo "===== $name =====" + docker exec -i "$name" python3 < /tmp/_verify_tm_inner.py +done +''' + + +def run(label, host, port, user, pw, sudo): + print(f"\n########## {label} ##########", flush=True) + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_verify_tm_inner.py", "wb") as f: + f.write(INNER.encode()) + with sftp.file("/tmp/_verify_tm_all.sh", "wb") as f: + f.write(REMOTE.encode()) + sftp.close() + cmd = f"echo {pw} | sudo -S -p '' bash /tmp/_verify_tm_all.sh" if sudo else "bash /tmp/_verify_tm_all.sh" + _, o, e = c.exec_command(cmd, timeout=300) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + + +run("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True) +run("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False) diff --git a/scripts/_verify_batch2.py b/scripts/_verify_batch2.py new file mode 100644 index 0000000..216d4c3 --- /dev/null +++ b/scripts/_verify_batch2.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +import paramiko +PASS = "Xiao4669805" +CMD = r""" +curl -sS -m 4 -o /dev/null -w 'health:%{http_code}\n' http://127.0.0.1:8014/api/health +systemctl is-active douyinweb-api douyinweb-web +systemctl is-active douyinweb-neko-watch.service 2>/dev/null || echo no_watch_unit +grep -c cdp_ok /usr/local/bin/neko_health_watch.sh 2>/dev/null || echo 0 +pgrep -af neko_health_watch || true +""" +for label, host in [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")]: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=35, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command(CMD, timeout=40) + print("====", label) + print((o.read() + e.read()).decode()) + c.close() diff --git a/scripts/_verify_both_health.py b/scripts/_verify_both_health.py new file mode 100644 index 0000000..a367ca0 --- /dev/null +++ b/scripts/_verify_both_health.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=40, + banner_timeout=80, + allow_agent=False, + look_for_keys=False, +) +cmd = r""" +set +e +echo '--- health ---' +curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\n' https://dylive.nomadro.com/api/health +curl -sS -m 20 -o /dev/null -w 'dy_com=%{http_code}\n' https://dy.nomadro.com/api/health +curl -sS -m 20 -o /dev/null -w 'dy_cn=%{http_code}\n' https://dy.nomadro.cn/api/health +echo '--- dylive rev ---' +cd /opt/douyinWEB && git log -1 --oneline +curl -sS -m 10 http://127.0.0.1:8014/api/ops/host-profile +echo +""" +_i, o, e = c.exec_command(cmd, timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_covers_smoke.py b/scripts/_verify_covers_smoke.py new file mode 100644 index 0000000..8f953ae --- /dev/null +++ b/scripts/_verify_covers_smoke.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Final smoke: login + active sessions cover fields on both sites.""" +from __future__ import annotations + +import json +import ssl +import sys +import urllib.request +from http.cookiejar import CookieJar + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +CTX = ssl.create_default_context() + + +def probe(site: str): + print(f"\n=== {site} ===", flush=True) + cj = CookieJar() + opener = urllib.request.build_opener( + urllib.request.HTTPSHandler(context=CTX), + urllib.request.HTTPCookieProcessor(cj), + ) + body = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + site + "/api/auth/login", + data=body, + headers={"Content-Type": "application/json"}, + method="POST", + ) + with opener.open(req, timeout=25) as r: + print("login", r.status) + with opener.open(site + "/api/sessions/active", timeout=30) as r: + data = json.loads(r.read().decode()) + items = data.get("sessions") or [] + print("active", len(items)) + ok_img = 0 + for it in items[:8]: + cover = (it.get("cover_url") or it.get("cover_proxy_url") or "").strip() + avatar = (it.get("avatar_url") or "").strip() + src = avatar if avatar.startswith("http") else cover + status = "-" + if src.startswith("http"): + url = src + elif src.startswith("/"): + url = site + src + else: + url = "" + if url: + try: + with opener.open(url, timeout=15) as ir: + status = f"{ir.status}:{ir.headers.get('content-type','')[:24]}" + if ir.status == 200: + ok_img += 1 + except Exception as e: + status = f"ERR:{e}" + print( + { + "id": str(it.get("id") or "")[:8], + "avatar": avatar[:60], + "cover": cover[:50], + "fetch": status, + } + ) + print("ok_img_among_sampled", ok_img) + + +for s in ("https://dylive.nomadro.com", "https://dy.nomadro.live"): + probe(s) +print("ALL_DONE", flush=True) diff --git a/scripts/_verify_dual_keys_neko.py b/scripts/_verify_dual_keys_neko.py new file mode 100644 index 0000000..7972986 --- /dev/null +++ b/scripts/_verify_dual_keys_neko.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Dual verify: keys API/UI + timeslot neko health on dy + dylive.""" +from __future__ import annotations + +import json +import ssl +import sys +import time +import urllib.error +import urllib.request +from http.cookiejar import CookieJar + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SITES = [ + ("dy", "https://dy.nomadro.live", "108.174.50.68", "douyinweb-neko-10"), + ("dylive", "https://dylive.nomadro.com", "107.173.30.245", "douyinweb-neko-12"), +] +USER = "hackrobot" +PASS = "Xiao4669805@" +SSH_PASS = "Xiao4669805" +CTX = ssl.create_default_context() + + +def login_opener(base: str): + cj = CookieJar() + op = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(cj), + urllib.request.HTTPSHandler(context=CTX), + ) + req = urllib.request.Request( + f"{base}/api/auth/login", + data=json.dumps({"username": USER, "password": PASS}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with op.open(req, timeout=45) as r: + body = r.read().decode("utf-8", "replace") + print(f" login {r.status} {body[:120]}") + return op + + +def get(op, url: str): + try: + with op.open(url, timeout=45) as r: + raw = r.read() + return r.status, raw + except urllib.error.HTTPError as e: + return e.code, e.read() + except Exception as e: + return 0, str(e).encode() + + +def ssh_check(host: str, neko: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + SSH_PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + break + except Exception as e: + print(f" ssh_retry {i}: {e}") + time.sleep(2 + i) + else: + return "ssh_fail" + cmd = f""" +set +e +docker ps --filter name={neko} --format '{{{{.Names}}}} {{{{.Status}}}}' +docker exec {neko} sh -c ' +supervisorctl status google-chrome 2>/dev/null | head -1 +grep -n "js-flags" /etc/neko/browser-launch.sh | head -1 +curl -sS -m 3 http://127.0.0.1:9222/json/version 2>/dev/null | head -c 100; echo +python3 - <<"PY" +import json,urllib.request +try: + tabs=json.load(urllib.request.urlopen("http://127.0.0.1:9222/json",timeout=5)) + studio=[t for t in tabs if "studio.youtube" in (t.get("url") or "")] + print("tabs",len(tabs),"studio",len(studio)) + for t in studio[:2]: + print(" ", (t.get("url") or "")[:100]) +except Exception as e: + print("tabs_err",e) +PY +' +# free mem snapshot +free -m | head -2 +docker ps --format '{{{{.Names}}}} {{{{.Status}}}}' | grep -v douyinweb | head -20 +""" + _i, o, e = c.exec_command(cmd, timeout=90) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +def main(): + for name, base, host, neko in SITES: + print(f"\n======== {name} {base} ========", flush=True) + op = login_opener(base) + for path in ("/youtube", "/youtube/keys"): + st, raw = get(op, base + path) + text = raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else str(raw) + hit = "youtube/keys" in text or "stream-key" in text or "Key" in text or "key表" in text + print(f" GET {path} -> {st} bytes={len(raw) if isinstance(raw, (bytes, bytearray)) else 0} hint={hit}") + + st, raw = get(op, base + "/api/youtube/stream-keys") + try: + data = json.loads(raw.decode() if isinstance(raw, (bytes, bytearray)) else raw) + except Exception: + data = {"_raw": (raw[:200] if isinstance(raw, (bytes, bytearray)) else raw)} + items = data.get("items") or data.get("keys") or data if isinstance(data, list) else [] + if isinstance(data, dict) and not items: + # try nested + for k in ("data", "registry", "entries"): + if isinstance(data.get(k), list): + items = data[k] + break + print(f" stream-keys API {st} type={type(data).__name__} items={len(items) if isinstance(items, list) else '?'}") + if isinstance(items, list) and items: + sample = items[0] if isinstance(items[0], dict) else {} + sk = sample.get("stream_key") or sample.get("key") or "" + print(f" sample keys={list(sample.keys())[:12]} stream_key_len={len(str(sk))} prefix={(str(sk)[:6]+'…') if sk else 'EMPTY'}") + + st, raw = get(op, base + "/api/youtube/assign/groups?include_secret=1") + try: + groups = json.loads(raw.decode() if isinstance(raw, (bytes, bytearray)) else raw) + except Exception: + groups = [] + if isinstance(groups, dict): + groups = groups.get("groups") or groups.get("items") or [] + full = 0 + masked = 0 + if isinstance(groups, list): + for g in groups: + if not isinstance(g, dict): + continue + sk = str(g.get("stream_key") or "") + if not sk: + continue + if "*" in sk or sk.endswith("…") or len(sk) < 12: + masked += 1 + else: + full += 1 + print(f" assign groups {st} n={len(groups)} full_keys={full} masked_or_short={masked}") + else: + print(f" assign groups {st} unexpected {type(groups)}") + + print(" --- neko ---") + print(ssh_check(host, neko)) + + print("\nALL_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/_verify_dy_login.py b/scripts/_verify_dy_login.py new file mode 100644 index 0000000..bb22bf8 --- /dev/null +++ b/scripts/_verify_dy_login.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +cmd = r""" +set +e +for i in 1 2 3 4 5 6 7 8 9 10; do + echo try $i $(systemctl is-active douyinweb-api) $(systemctl is-active douyinweb-web) + if curl -fsS http://127.0.0.1:8014/api/health >/tmp/h.json; then + break + fi + sleep 2 +done +head -c 220 /tmp/h.json; echo +curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/l.json -w 'login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \ + -H 'Content-Type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' +cat /tmp/l.json; echo +curl -sS -o /dev/null -w 'page:%{http_code}\n' https://dy.nomadro.live/login +""" +_i, o, e = c.exec_command(cmd, timeout=90) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_dy_neko7_stable.py b/scripts/_verify_dy_neko7_stable.py new file mode 100644 index 0000000..cdc8ece --- /dev/null +++ b/scripts/_verify_dy_neko7_stable.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Re-check neko-7 Studio stays up 45s after jitless; sync flags to other running nekos.""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, +) + +cmd = r""" +set +e +# wait and poll studio tab health +docker exec douyinweb-neko-7 python3 - <<'PY' +import json, urllib.request, time +def tabs(): + return json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +for i in range(10): + pages=[t for t in tabs() if t.get("type")=="page"] + titles=" | ".join((t.get("title") or "")[:40] for t in pages) + urls=" | ".join((t.get("url") or "")[:60] for t in pages) + bad=any(x in titles for x in ("Snap","SIGILL","Can't open","Cant open")) or any("chrome-error" in (t.get("url") or "") for t in pages) + print("poll", i, "bad="+str(bad), titles) + print(" urls", urls) + if bad: + print("REGRESSED") + break + time.sleep(5) +else: + print("STABLE_45S") +print("traps_new:") +PY +dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -3 +# restart chrome on other running with same script (already synced file) +for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do + docker exec "$name" grep -q jitless /etc/neko/browser-launch.sh && echo OK_$name || echo STALE_$name + if [ "$name" != "douyinweb-neko-7" ]; then + docker exec "$name" supervisorctl restart google-chrome >/dev/null 2>&1 || true + fi +done +sleep 3 +docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' +free -h | head -2 +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_dy_nomadro_edge.py b/scripts/_verify_dy_nomadro_edge.py new file mode 100644 index 0000000..8d9a06a --- /dev/null +++ b/scripts/_verify_dy_nomadro_edge.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Verify dy.nomadro.com path is intact; ensure edge deps stay up.""" +from __future__ import annotations + +import sys +import time + +import httpx +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(): + last = None + for i in range(12): + try: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=60, + banner_timeout=180, + allow_agent=False, + look_for_keys=False, + ) + print("connected", i, flush=True) + return c + except Exception as ex: + last = ex + print("retry", i, type(ex).__name__, ex, flush=True) + time.sleep(5) + raise SystemExit(f"ssh failed: {last}") + + +def run(c, cmd, t=90): + print(f"\n$ {cmd[:240]}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=t) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-7000:] if len(out) > 7000 else out, flush=True) + return code, out + + +def main() -> int: + print("=== public probes ===", flush=True) + with httpx.Client(follow_redirects=False, timeout=25, verify=True) as cl: + for url in [ + "https://dy.nomadro.com/", + "https://dy.nomadro.com/api/health", + "https://dy.nomadro.com/login", + "https://dylive.nomadro.com/api/health", + ]: + try: + r = cl.get(url) + loc = r.headers.get("location", "") + print(f"{url} -> {r.status_code} loc={loc[:80]}", flush=True) + except Exception as ex: + print(f"{url} ERR {ex}", flush=True) + + c = connect() + try: + # Ensure physical edge deps are running (do NOT touch stopped product stacks) + run( + c, + "systemctl start caddy nginx 'wg-quick@wg-dy' frpp docker 2>/dev/null; " + "systemctl is-active caddy nginx 'wg-quick@wg-dy' frpp docker douyinweb-api douyinweb-web; " + "wg show wg-dy 2>/dev/null | head -20", + 60, + ) + run( + c, + "grep -Rne 'dy.nomadro.com\\|10.8.0.2' /etc/caddy /etc/caddy/Caddyfile* 2>/dev/null | head -40; " + "ls /etc/caddy 2>/dev/null; " + "curl -sS -m 10 -o /dev/null -w 'via_wg=%{http_code}\\n' http://10.8.0.2:8014/api/health || echo via_wg_fail; " + "curl -sS -m 10 -o /dev/null -w 'via_wg_web=%{http_code}\\n' http://10.8.0.2:4015/ || echo via_wg_web_fail", + 40, + ) + # Confirm product nomadro units stay stopped (unrelated to dy.nomadro.com) + run( + c, + "echo 'product nomadro (should stay stopped):'; " + "for u in nomadro nomadro-api nomadro-web nomadro-router nomadro-live-router; do " + " printf '%s %s\\n' $u $(systemctl is-active $u 2>/dev/null); " + "done", + 30, + ) + print("\nDONE", flush=True) + return 0 + finally: + c.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_verify_dylive_neko12_sigill.py b/scripts/_verify_dylive_neko12_sigill.py new file mode 100644 index 0000000..d768c71 --- /dev/null +++ b/scripts/_verify_dylive_neko12_sigill.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Verify neko-12 chrome flags + open Studio via CDP.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) + +cmd = r""" +set +e +echo '=== mounted flags ===' +docker exec douyinweb-neko-12 grep -n 'no-wasm-simd\|WebAssemblySimd\|max-old-space' /etc/neko/browser-launch.sh +echo '=== chrome cmdline snippet ===' +docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null) + case "$cmd" in + *remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "js-flags|wasm|WebAssembly|max-old|remote-debugging" ; echo "---"; break ;; + esac +done' +echo '=== CDP ===' +docker exec douyinweb-neko-12 python3 -c ' +import json, urllib.request, time +STUDIO="https://studio.youtube.com/channel/UCfP5vcTQEfrHc13yTmmokQw/livestreaming" +for i in range(20): + try: + urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=2).read() + print("devtools_ok") + break + except Exception as e: + time.sleep(1) +else: + raise SystemExit("no_devtools") +# try new tab +ok=False +for method in ("PUT","GET"): + try: + req=urllib.request.Request("http://127.0.0.1:9222/json/new?"+STUDIO, method=method) + body=urllib.request.urlopen(req, timeout=15).read() + print("opened", method, body[:160]) + ok=True + break + except Exception as e: + print("fail", method, e) +time.sleep(8) +tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read()) +for t in tabs: + if t.get("type")=="page": + title=(t.get("title") or "")[:80] + url=(t.get("url") or "")[:140] + print("TAB", title, "|", url) +' +echo '=== recent traps ===' +dmesg -T 2>/dev/null | grep -i "invalid opcode" | tail -3 +free -h | head -3 +""" +_i, o, e = c.exec_command(cmd, timeout=120) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_opsneko_now.py b/scripts/_verify_opsneko_now.py new file mode 100644 index 0000000..621b43a --- /dev/null +++ b/scripts/_verify_opsneko_now.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +def one(host, port, user, pw, cmd, t=60): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + +print("=== VPS ===", flush=True) +print(one("107.173.30.245", 22, "root", "Xiao4669805", + "systemctl is-active douyinweb-api; " + "systemctl is-active dy-frp-http-aux sing-box frpp 'wg-quick@wg-dy'; " + "curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " + "curl -sS -m 15 -o /dev/null -w 'dy=%{http_code}\\n' https://dy.nomadro.com/api/health; " + "curl -sS -m 15 -o /dev/null -w 'ops=%{http_code}\\n' https://dy.nomadro.com/ops-neko/1/; " + "ss -lntp | grep -E '18200|14015|18014' | head -5", + 90), flush=True) + +print("=== CN ===", flush=True) +print(one("82.157.112.245", 22, "ubuntu", "Xiao4669805", + "curl -sS -m 12 -o /dev/null -w 'cn_ops=%{http_code}\\n' https://dy.nomadro.cn/ops-neko/1/; " + "curl -sS -m 12 -o /dev/null -w 'cn_api=%{http_code}\\n' https://dy.nomadro.cn/api/health; " + "sudo iptables -t nat -S | grep -E '62300|OPS-NEKO' | head -6", + 40), flush=True) + +print("=== PHYS chrome ===", flush=True) +print(one("107.173.30.245", 4014, "eric", "4669805", + "echo '4669805' | sudo -S -p '' docker exec douyinweb-ops-neko-1 supervisorctl status google-chrome; " + "echo '4669805' | sudo -S -p '' curl -sS -m 5 -o /dev/null -w 'ops=%{http_code}\\n' http://127.0.0.1:18200/; " + "echo '4669805' | sudo -S -p '' systemctl is-active douyinweb-api", + 40), flush=True) diff --git a/scripts/_verify_opsneko_tm_after_repair.py b/scripts/_verify_opsneko_tm_after_repair.py new file mode 100644 index 0000000..3e25fc2 --- /dev/null +++ b/scripts/_verify_opsneko_tm_after_repair.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +CMD = r""" +echo 4669805 | sudo -S -p '' bash -lc ' +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +for i in 1 2; do + echo "===== OPS$i =====" + docker exec douyinweb-ops-neko-$i bash -lc " + P=/home/neko/.config/google-chrome/Default + echo --- sizes --- + du -sh \"\$P/Local Extension Settings/$EXT\" \"\$P/Managed Extension Settings/$EXT\" 2>/dev/null + ls -la \"\$P/Local Extension Settings/$EXT\" 2>/dev/null | head + ls -la \"\$P/Managed Extension Settings/$EXT\" 2>/dev/null | head + echo --- managed strings --- + strings \"\$P/Managed Extension Settings/$EXT\"/* 2>/dev/null | grep -E \"YouTube Studio|Auto Dismiss|2\\.2\\.|error|hash|jsonImport|557378\" | head -20 + echo --- policy hash inside container --- + python3 -c \"import json; d=json.load(open(\\\"/etc/opt/chrome/policies/managed/policies.json\\\")); print(d[\\\"3rdparty\\\"][\\\"extensions\\\"][\\\"$EXT\\\"][\\\"jsonImport\\\"][0])\" + echo --- provisioning hash --- + curl -fsS http://127.0.0.1:18080/tampermonkey-provisioning.json >/tmp/p.json + python3 - <<'"'"'PY'"'"' +import json, hashlib, sys +from pathlib import Path +# quick compare name +d=json.load(open(\"/tmp/p.json\")) +print(\"script\", d[\"scripts\"][0][\"name\"], \"ver_in_b64_head\", d[\"scripts\"][0][\"source\"][:40]) +PY + " +done +# give TM more time then second chrome bounce +for i in 1 2; do + docker exec douyinweb-ops-neko-$i supervisorctl restart google-chrome || true +done +sleep 25 +for i in 1 2; do + echo "===== AFTER RESTART OPS$i =====" + docker exec douyinweb-ops-neko-$i bash -lc " + P=/home/neko/.config/google-chrome/Default + du -sh \"\$P/Local Extension Settings/$EXT\" \"\$P/Managed Extension Settings/$EXT\" 2>/dev/null + echo HITS=\$(grep -aR \"YouTube Studio Auto Dismiss\" \"\$P/Local Extension Settings/$EXT\" \"\$P/Managed Extension Settings/$EXT\" 2>/dev/null | wc -l) + strings \"\$P/Local Extension Settings/$EXT\"/* 2>/dev/null | grep -E \"YouTube Studio Auto Dismiss|2\\.2\\.1\" | head -5 || echo NO_IN_LES + strings \"\$P/Managed Extension Settings/$EXT\"/* 2>/dev/null | grep -E \"YouTube Studio Auto Dismiss|2\\.2\\.1\" | head -5 || echo NO_IN_MAN + " +done +' +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False) + _i, o, e = c.exec_command(CMD, timeout=200) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_verify_phys_tm_now.py b/scripts/_verify_phys_tm_now.py new file mode 100644 index 0000000..ee64e54 --- /dev/null +++ b/scripts/_verify_phys_tm_now.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, +) +_i, o, e = c.exec_command( + r""" +echo '4669805' | sudo -S -p '' bash -lc ' +set +e +EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo +P=/opt/douyinWEB/backend/data/neko/profiles +OP=/opt/douyinWEB/backend/data/ops_neko/profiles +echo "=== host TM dirs ===" +for id in 1 2 3 4 5 6 7 8; do + printf "neko-%s TM=%s dismiss=" "$id" + test -d "$P/$id/Default/Extensions/$EXT/5.5.0_0" && echo -n YES || echo -n NO + if grep -R -a -q "YouTube Studio Auto Dismiss" "$P/$id/Default/Local Extension Settings/$EXT" 2>/dev/null; then echo YES; else echo NO; fi +done +for id in 1 2; do + printf "ops-%s TM=%s dismiss=" "$id" + test -d "$OP/$id/Default/Extensions/$EXT/5.5.0_0" && echo -n YES || echo -n NO + if grep -R -a -q "YouTube Studio Auto Dismiss" "$OP/$id/Default/Local Extension Settings/$EXT" 2>/dev/null; then echo YES; else echo NO; fi +done +echo "=== chrome status ===" +for n in $(docker ps --format "{{.Names}}" | grep -E "douyinweb-(neko|ops-neko)-" | sort); do + st=$(docker exec "$n" supervisorctl status google-chrome 2>/dev/null | awk "{print \$2}") + echo "$n $st" +done +echo "=== in-container TM for neko-1/3/7 ops-1 ===" +for n in douyinweb-neko-1 douyinweb-neko-3 douyinweb-neko-7 douyinweb-ops-neko-1; do + docker exec "$n" bash -lc "test -f /home/neko/.config/google-chrome/Default/Extensions/$EXT/5.5.0_0/manifest.json && echo $n EXT_OK || echo $n EXT_MISS" +done +' +""", + timeout=120, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_physical_api.py b/scripts/_verify_physical_api.py new file mode 100644 index 0000000..c464e9d --- /dev/null +++ b/scripts/_verify_physical_api.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect( + "107.173.30.245", + 4014, + "eric", + "4669805", + timeout=40, + banner_timeout=80, + allow_agent=False, + look_for_keys=False, +) +cmd = r"""echo '4669805' | sudo -S -p '' bash -lc ' +git config --global --add safe.directory /opt/douyinWEB 2>/dev/null || true +cd /opt/douyinWEB && git log -1 --oneline +curl -sS -m 10 --noproxy "*" http://127.0.0.1:8014/api/health | head -c 200; echo +curl -sS -m 10 --noproxy "*" http://127.0.0.1:8014/api/ops/host-profile | head -c 400; echo +systemctl is-active douyinweb-api douyinweb-web +' +""" +_i, o, e = c.exec_command(cmd, timeout=60) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_safe_heal_and_tt.py b/scripts/_verify_safe_heal_and_tt.py new file mode 100644 index 0000000..9fe286d --- /dev/null +++ b/scripts/_verify_safe_heal_and_tt.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Post-deploy verify + tiktok optimistic toggle FE.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")] +LOCAL_TT = ROOT / "frontend" / "src" / "app" / "tiktok" / "page.tsx" + +VERIFY = r''' +cd /opt/douyinWEB/backend +.venv/bin/python <<'PY' +from app.youtube_neko import heal_crashed_assign_nekos, _neko_ids_needed_for_live, _container_state +from app.yt_long_db import list_pending_yt_long_jobs +from app.youtube_relay_pipeline import youtube_relay_pipeline +import json +print("needed", sorted(_neko_ids_needed_for_live())) +print("heal", json.dumps(heal_crashed_assign_nekos(), ensure_ascii=False)[:500]) +pend = list_pending_yt_long_jobs(limit=8) +empty = sum(1 for j in pend if not str(j.get("channel_pk") or "").strip()) +print("pending", len(pend), "empty_channel", empty) +st = youtube_relay_pipeline.status() +print("relay_pushing", st.get("pushing_count"), "running", st.get("running")) +for nid in sorted(_neko_ids_needed_for_live())[:5]: + s = _container_state(nid) + print("neko", nid, "run", s.get("running"), "oom", s.get("oom_killed"), "st", s.get("status")) +PY +curl -sS -m 5 -o /dev/null -w 'health:%{http_code}\n' http://127.0.0.1:8014/api/health +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print(f"ssh_retry {host} {i}: {e}", flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def run(c, cmd, t=120): + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + +for label, host in HOSTS: + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + data = LOCAL_TT.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + with sftp.file("/tmp/_tiktok_page.tsx", "wb") as f: + f.write(data) + sftp.close() + print(run(c, "cat /tmp/_tiktok_page.tsx > /opt/douyinWEB/frontend/src/app/tiktok/page.tsx && echo TT_OK", 20), flush=True) + print(run(c, "cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -8; systemctl restart douyinweb-web; sleep 2; systemctl is-active douyinweb-web", 400), flush=True) + print(run(c, VERIFY, 90), flush=True) + c.close() diff --git a/scripts/_verify_shellcrash_tuic.py b/scripts/_verify_shellcrash_tuic.py new file mode 100644 index 0000000..4c8af7d --- /dev/null +++ b/scripts/_verify_shellcrash_tuic.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""Verify TUIC guard + selection on phys + VPS.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def ssh(label, host, port, user, pw, sudo=False): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=40, allow_agent=False, look_for_keys=False) + + def run(cmd, t=60): + if sudo: + cmd = f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}" + _, o, e = c.exec_command(cmd, timeout=t) + return (o.read() + e.read()).decode("utf-8", "replace") + + print(run( + "systemctl is-active douyinweb-shellcrash-tuic-guard.service douyinweb-api.service; " + "systemctl is-active shellcrash.service 2>/dev/null; " + "systemctl --no-pager -l status douyinweb-shellcrash-tuic-guard.service 2>/dev/null | sed -n '1,18p'" + )) + print(run( + "curl -sS -m 5 http://127.0.0.1:9999/proxies | python3 -c " + "\"import sys,json; d=json.load(sys.stdin); ps=d.get('proxies') or {}; " + "print('now', (ps.get('🚀 节点选择') or {}).get('now') or (ps.get('GLOBAL') or {}).get('now')); " + "print('tuic_delay', end=' ');\" 2>/dev/null; " + "curl -sS -m 8 'http://127.0.0.1:9999/proxies/1d2da142-singbox_tuic5/delay?timeout=5000&url=http://www.gstatic.com/generate_204' || echo delay_fail" + )) + print(run( + "systemctl show douyinweb-api -p Environment --no-pager | tr ' ' '\\n' | grep SHELLCRASH || true" + )) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/network/shellcrash/status"), timeout=40) as r: + d = json.loads(r.read().decode()) + sc = d.get("shellcrash") or d + print( + base, + "running=", sc.get("running"), + "selected=", sc.get("selected_node"), + "family=", sc.get("selected_family"), + "default=", sc.get("default_node"), + "allow_vless=", sc.get("allow_vless_autopick"), + "unit=", sc.get("unit"), + ) + + +ssh("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True) +ssh("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) +print("\n===== public =====") +for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"): + try: + pub(b) + except Exception as e: + print(b, e) diff --git a/scripts/_verify_shorts_api_cooldown.py b/scripts/_verify_shorts_api_cooldown.py new file mode 100644 index 0000000..1334b7e --- /dev/null +++ b/scripts/_verify_shorts_api_cooldown.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +"""Defer due Client-B shorts uploads past cool-down; verify status.""" +from __future__ import annotations + +import json +import sys +import http.cookiejar +import urllib.request + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +PY = r''' +import time, sys, os +os.chdir("/opt/douyinWEB/backend") +sys.path.insert(0, "/opt/douyinWEB/backend") +from app.shorts_yt_quota import ( + blocked_profile_ids, + defer_profile_shorts_uploads, + profile_upload_blocked, +) +from app import db + +cfg = db.get_settings_map() +for pid in ("A", "B", "C", "D"): + blocked, until = profile_upload_blocked(cfg, profile_id=pid) + if blocked or pid in ("A", "B"): + left = max(0, int((until - time.time()) / 60)) if until else 0 + print(f"profile {pid} blocked={blocked} left_min={left}") +print("blocked_ids", sorted(blocked_profile_ids(cfg))) +blocked, until = profile_upload_blocked(cfg, profile_id="B") +if blocked and until > time.time(): + n = defer_profile_shorts_uploads("B", until, reason="Client B 接口配额冷静,稍后自动重试") + print("deferred_B", n) +else: + print("deferred_B", 0, "(no active B cool-down)") +''' + + +def run(label, host, port, user, pw, *, sudo): + print(f"\n===== {label} =====") + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_dy_defer_b.py", "w") as f: + f.write(PY.replace("\r\n", "\n")) + sftp.close() + py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_dy_defer_b.py" + cmd = f"echo '{pw}' | sudo -S -p '' {py}" if sudo else py + _, o, e = c.exec_command(cmd, timeout=120) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def pub(base): + cj = http.cookiejar.CookieJar() + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode() + req = urllib.request.Request( + base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"} + ) + op.open(req, timeout=30) + with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r: + st = json.loads(r.read().decode()) + print( + base, + "blocked=", st.get("upload_quota_blocked"), + "profiles=", st.get("upload_quota_blocked_profiles"), + "cooldown_sec=", st.get("yt_quota_cooldown_sec"), + "uploads=", st.get("active_uploads"), + ) + + +if __name__ == "__main__": + run("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False) + run("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True) + print("\n===== public =====") + pub("https://dylive.nomadro.com") + pub("https://dy.nomadro.com") diff --git a/scripts/_verify_timeslot_exclude_api.py b/scripts/_verify_timeslot_exclude_api.py new file mode 100644 index 0000000..eb81358 --- /dev/null +++ b/scripts/_verify_timeslot_exclude_api.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +import paramiko + +SCRIPT = r''' +import json, urllib.request, http.cookiejar, time +for i in range(10): + try: + code = urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=3).status + print("health", code) + break + except Exception as e: + print("wait", i, type(e).__name__) + time.sleep(2) +else: + print("health FAIL") +cj = http.cookiejar.CookieJar() +op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req = urllib.request.Request( + "http://127.0.0.1:8014/api/auth/login", + data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", +) +print("login", op.open(req, timeout=10).status) +p = json.loads(op.open("http://127.0.0.1:8014/api/youtube/assign/timeslot-exclude", timeout=20).read()) +print("exclude", p.get("ok"), "count", p.get("count"), "effective", p.get("effective_room_count")) +''' + + +def check(port, user, pwd, label, sudo=False): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", port, user, pwd, timeout=20) + if sudo: + sftp = c.open_sftp() + with sftp.file("/tmp/_v_tex2.py", "w") as f: + f.write(SCRIPT) + sftp.close() + cmd = f"echo '{pwd}' | sudo -S -p '' python3 /tmp/_v_tex2.py" + _, o, e = c.exec_command(cmd, timeout=80) + else: + _, o, e = c.exec_command("python3 -", timeout=80) + o.channel.sendall(SCRIPT.encode()) + o.channel.shutdown_write() + print("====", label, "====") + print(o.read().decode("utf-8", "replace")) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print(err[-400:]) + c.close() + + +if __name__ == "__main__": + check(22, "root", "Xiao4669805", "vps") + check(4014, "eric", "4669805", "phys", sudo=True) diff --git a/scripts/_verify_tm_dual_revive.py b/scripts/_verify_tm_dual_revive.py new file mode 100644 index 0000000..21588e7 --- /dev/null +++ b/scripts/_verify_tm_dual_revive.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Verify TM on both hosts; revive neko-2 if needed (docker start only).""" +from __future__ import annotations + +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def connect(host): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect( + host, + 22, + "root", + "Xiao4669805", + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=180, + ) + return c + except Exception as e: + print("retry", host, i, e) + time.sleep(2) + raise SystemExit("fail") + + +def run(c, cmd, t=120): + _i, o, e = c.exec_command(cmd, timeout=t) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + + +cmd = r""" +set +e +echo '--- containers ---' +docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V +# ensure neko-2 up if assign wants it (hackrobotlite) +if docker inspect douyinweb-neko-2 >/dev/null 2>&1; then + if ! docker inspect -f '{{.State.Running}}' douyinweb-neko-2 | grep -q true; then + echo 'starting neko-2' + docker start douyinweb-neko-2 + sleep 10 + fi +fi +for name in $(docker ps --format '{{.Names}}' | grep '^douyinweb-neko-' | sort -V); do + docker exec "$name" python3 -c " +import os,re +p='/home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +b=b'' +for r,_,fs in os.walk(p): + for f in fs: + try: b+=open(os.path.join(r,f),'rb').read() + except: pass +print('$name', 'OK' if b'YouTube Studio Auto Dismiss' in b else 'EMPTY', 'blob', len(b)) +" 2>&1 + docker exec "$name" supervisorctl status google-chrome 2>&1 | head -1 +done +# seed check +SEED='/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo' +echo -n 'seed '; grep -a -R -q 'YouTube Studio Auto Dismiss' \"$SEED\" && echo OK || echo EMPTY +curl -sS -m 5 -o /dev/null -w 'neko2_http:%{http_code}\n' http://127.0.0.1:9201/ 2>/dev/null || true +""" + +print("===== dylive =====", flush=True) +dl = connect("107.173.30.245") +run(dl, cmd) +dl.close() + +print("===== dy =====", flush=True) +dy = connect("108.174.50.68") +run(dy, cmd.replace("9201", "9209")) # just don't care about port on dy +dy.close() +print("DONE") diff --git a/scripts/_verify_vps_api_health.py b/scripts/_verify_vps_api_health.py new file mode 100644 index 0000000..b811e32 --- /dev/null +++ b/scripts/_verify_vps_api_health.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +import paramiko +import sys + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) +_i, o, e = c.exec_command( + "systemctl is-active douyinweb-api; " + "curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 180; echo; " + "curl -sS -m 8 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health", + timeout=40, +) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_verify_vps_live3.py b/scripts/_verify_vps_live3.py new file mode 100644 index 0000000..451765d --- /dev/null +++ b/scripts/_verify_vps_live3.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +import json +import urllib.request +import http.cookiejar +import sqlite3 + +import paramiko + +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25) +script = r''' +import json,urllib.request,http.cookiejar,sqlite3 +con=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") +rows=list(con.execute("select ts,youtube_channel_id,on_air,live_status,detect_source,neko_ref,group_id from yt_studio_samples where detect_source='edge_assign_live' or on_air=1 order by ts desc limit 15")) +print("samples", len(rows)) +for r in rows: + print(r) +cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +req=urllib.request.Request("http://127.0.0.1:8014/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST") +print("login", op.open(req,timeout=10).status) +p=json.loads(op.open("http://127.0.0.1:8014/api/youtube/live-map?force=1", timeout=150).read()) +print("vps live_count", p.get("live_count"), p.get("source")) +for k,v in sorted((p.get("entries") or {}).items()): + if v.get("is_live") and str(k).startswith("assign:"): + print(" LIVE", (v.get("title") or k)[:30], v.get("source"), (v.get("live_url") or "")[:60]) +''' +stdin, stdout, stderr = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python -", timeout=200) +stdin.write(script) +stdin.channel.shutdown_write() +print(stdout.read().decode("utf-8", "replace")) +print(stderr.read().decode("utf-8", "replace")[-800:]) +c.close() diff --git a/scripts/_vps_bind_relay_ro.py b/scripts/_vps_bind_relay_ro.py new file mode 100644 index 0000000..4a6baa9 --- /dev/null +++ b/scripts/_vps_bind_relay_ro.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""VPS: binds + relay/studio gate state (read-only).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +python3 - <<'PY' +import sqlite3, json, time +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +print('=== assign groups ===') +cols=[r[1] for r in con.execute('PRAGMA table_info(yt_assign_groups)')] +print('cols', [c for c in cols if 'neko' in c.lower() or 'ops' in c.lower()]) +rows=con.execute('SELECT * FROM yt_assign_groups ORDER BY neko_instance_id').fetchall() +now=time.time() +for r in rows: + d=dict(r) + print(f"#{d.get('neko_instance_id')} en={d.get('neko_enabled')} prefer={d.get('neko_open_prefer')} name={d.get('name')}") + print(f" ops_url={d.get('ops_neko_open_url')} slot={d.get('ops_neko_slot')} edge={d.get('ops_neko_edge_label')} bound_at={d.get('ops_neko_bound_at')}") + +print('=== yt_relay_states (recent) ===') +try: + rs=con.execute('SELECT * FROM yt_relay_states ORDER BY updated_at DESC LIMIT 8').fetchall() + for r in rs: + d=dict(r) + keep={k:d.get(k) for k in d if k in ('group_id','group_name','phase','reason','pushing','studio_live','updated_at','error','active','mode') or True} + # print compact + print({k:d[k] for k in d.keys() if k in d and (k in ('group_id','name','status','phase','reason','updated_at','message','pushing','live','error') or 'studio' in k or 'neko' in k or 'relay' in k)}) +except Exception as e: + print('relay_states_err', e) + print([r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE name LIKE '%relay%'")]) + +print('=== yt_studio_samples latest per key ===') +try: + info=con.execute('PRAGMA table_info(yt_studio_samples)').fetchall() + print('studio_cols', [x[1] for x in info]) + rows=con.execute('SELECT * FROM yt_studio_samples ORDER BY received_at DESC LIMIT 10').fetchall() + for r in rows: + d=dict(r) + print({k:d.get(k) for k in list(d.keys())[:20]}) +except Exception as e: + print('studio_err', e) + +print('=== ops_neko_edge_catalog ===') +try: + for r in con.execute('SELECT * FROM ops_neko_edge_catalog').fetchall(): + print(dict(r)) +except Exception as e: + print(e) + +print('=== ops_neko_instances ===') +try: + for r in con.execute('SELECT * FROM ops_neko_instances').fetchall(): + print(dict(r)) +except Exception as e: + print(e) +PY + +echo '=== relay status API ===' +curl -sS -m 8 http://127.0.0.1:8014/api/youtube/relay/status 2>/dev/null | python3 -m json.tool 2>/dev/null | head -120 +echo '=== ops neko hub status ===' +curl -sS -m 8 http://127.0.0.1:8014/api/ops-neko/hub 2>/dev/null | head -c 1500; echo +curl -sS -m 8 http://127.0.0.1:8014/api/ops-neko/catalog 2>/dev/null | head -c 1500; echo +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_vps_bind_relay_ro.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_vps_bind_relay_ro.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")[:20000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_watch_push_and_key.py b/scripts/_watch_push_and_key.py new file mode 100644 index 0000000..79893c7 --- /dev/null +++ b/scripts/_watch_push_and_key.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Compare stream key suffix vs Studio + watch one start cycle.""" +from __future__ import annotations + +import json +import sys +import time + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +VPS = ("107.173.30.245", 22, "root", "Xiao4669805") +PHYS = ("107.173.30.245", 4014, "eric", "4669805") + + +def ssh(host, port, user, pwd, cmd, t=90): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, pwd, timeout=25, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command(cmd, timeout=t) + out = (o.read() + e.read()).decode("utf-8", "replace") + c.close() + return out + + +def main(): + print("=== VPS group key / rtmp (suffix only) ===") + print( + ssh( + *VPS, + r""" +cd /opt/douyinWEB/backend && python3 - <<'PY' +import sqlite3, re +con=sqlite3.connect('data/monitor.db') +con.row_factory=sqlite3.Row +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +g=dict(con.execute('select * from yt_assign_groups where id=?',(gid,)).fetchone() or {}) +# find key-ish columns +for k,v in g.items(): + if v is None: continue + s=str(v) + kl=k.lower() + if any(x in kl for x in ('key','rtmp','ingest','stream','youtube')): + if 'key' in kl or 'rtmp' in kl or 'ingest' in kl: + # redact + if len(s)>8: + print(k, 'len', len(s), 'tail4', s[-4:], 'head20', s[:20].replace('\n',' ')) + else: + print(k, s) + else: + print(k, s[:80]) +print('category', g.get('category'), 'enabled', g.get('enabled')) +# settings time slot +for row in con.execute("select key,value from settings where key like 'youtube_relay%' or key like '%exclusive%' or key like '%time_slot%'"): + print('set', row['key'], row['value']) +PY +""", + ) + ) + + print("=== PHYS CDP: studio key fragment + nodata ===") + print( + ssh( + *PHYS, + r""" +# use venv if present +PY=/opt/douyinWEB/backend/.venv/bin/python3 +[ -x "$PY" ] || PY=python3 +cd /opt/douyinWEB/backend +$PY - <<'PY' +import json, urllib.request +# try CDP scrape script if exists +import subprocess, os +os.chdir('/opt/douyinWEB') +# find ops-neko-1 cdp port +import docker +# fallback: docker inspect +out=subprocess.check_output(['docker','inspect','-f','{{range .NetworkSettings.Ports}}{{.}}{{end}}','douyinweb-ops-neko-1'], text=True, stderr=subprocess.DEVNULL) +print('ports_raw', out[:200]) +PY +# simpler: run existing cdp scrape via docker exec +docker exec douyinweb-ops-neko-1 bash -lc 'ls /home/neko 2>/dev/null | head' 2>/dev/null | head -5 +# host-side CDP +cd /opt/douyinWEB/backend +if [ -f .venv/bin/python ]; then .venv/bin/python neko/cdp_studio_scrape.py --slot 1 2>/dev/null | head -c 2500; else +python3 - <<'PY' +# locate chrome debug port for ops-neko-1 +import subprocess, re, json, urllib.request +name='douyinweb-ops-neko-1' +# get host mapped 9222? +insp=subprocess.check_output(['docker','inspect',name], text=True) +j=json.loads(insp)[0] +ports=j.get('NetworkSettings',{}).get('Ports') or {} +print('Ports', ports) +# try common host ports from labels/env +env={e.split('=',1)[0]:e.split('=',1)[1] for e in j.get('Config',{}).get('Env',[]) if '=' in e} +print('CDP related', {k:v for k,v in env.items() if 'CDP' in k.upper() or 'DEBUG' in k.upper() or '922' in v}) +# IP +ip=j['NetworkSettings']['IPAddress'] or list((j['NetworkSettings'].get('Networks') or {}).values())[0].get('IPAddress') +print('ip', ip) +for port in (9222, 9223, 35000, 35001): + try: + with urllib.request.urlopen(f'http://{ip}:{port}/json/list', timeout=2) as r: + tabs=json.loads(r.read().decode()) + print('cdp', port, 'tabs', len(tabs)) + for t in tabs: + u=t.get('url') or '' + if 'studio.youtube' in u or 'livestreaming' in u: + print(' TAB', u[:100], 'id', t.get('id')) + break + except Exception as ex: + print('fail', port, type(ex).__name__) +PY +fi +""", + 60, + ) + ) + + print("=== VPS: poll relay 45s ===") + print( + ssh( + *VPS, + r""" +cd /opt/douyinWEB/backend +python3 - <<'PY' +import sqlite3, json, time, os +gid='3fb8cbf7-2180-45bc-99f0-836169f0bf97' +for i in range(9): + con=sqlite3.connect('data/monitor.db') + con.row_factory=sqlite3.Row + r=dict(con.execute('select status,error,ffmpeg_pid,push_seconds,recent_log,updated_at from yt_relay_states where group_id=?',(gid,)).fetchone() or {}) + pid=int(r.get('ffmpeg_pid') or 0) + alive=bool(pid and os.path.exists(f'/proc/{pid}')) + log=r.get('recent_log') or '' + try: + lines=json.loads(log) if isinstance(log,str) and log.startswith('[') else str(log).splitlines() + except Exception: + lines=[] + tail=lines[-3:] if lines else [] + print(f"t+{i*5:02d}s", r.get('status'), 'pid', pid, 'alive', alive, 'push', r.get('push_seconds'), 'err', (r.get('error') or '')[:90]) + for ln in tail: + print(' ', (ln if isinstance(ln,str) else str(ln))[:160]) + time.sleep(5) +PY +""", + 70, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/_why_no_push_streetfood.py b/scripts/_why_no_push_streetfood.py new file mode 100644 index 0000000..fcff7b6 --- /dev/null +++ b/scripts/_why_no_push_streetfood.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Why asian streetfood stuck at 启动中 — prefer/gate/telemetry.""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +SCRIPT = r"""#!/bin/bash +set +e +python3 <<'PY' +import sqlite3, json, time +con=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db') +con.row_factory=sqlite3.Row +now=time.time() +print('=== groups matching streetfood / instance 7 ===') +for r in con.execute("select id,name,neko_instance_id,neko_enabled,neko_open_prefer,ops_neko_open_url,ops_neko_slot,ops_neko_edge_label,enabled,category from yt_assign_groups order by neko_instance_id"): + d=dict(r) + if 'street' in (d.get('name') or '').lower() or d.get('neko_instance_id') in (1,7) or d.get('ops_neko_slot')==1: + print(d) + +print('=== relay states for those groups ===') +for r in con.execute('select * from yt_relay_states'): + d=dict(r) + # print recent + print({k:d.get(k) for k in ('group_id','status','error','ffmpeg_pid','push_seconds','updated_at','started_at','anchor_name')}) + log=d.get('recent_log') + if log: + try: + lines=json.loads(log) if isinstance(log,str) and log.startswith('[') else str(log).split('\n') + except Exception: + lines=[str(log)[:200]] + for line in (lines[-12:] if isinstance(lines,list) else [lines]): + print(' LOG', str(line)[:160]) + +print('=== settings exclusive / relay ===') +for k in ('youtube_relay_enabled','youtube_relay_exclusive_live','youtube_relay_time_slot_mode','host_profile','youtube_relay_on_air_deadline_sec'): + row=con.execute('select value from kv_settings where key=?',(k,)).fetchone() + print(k, row['value'] if row else None) + +print('=== latest studio samples ops:1 ===') +try: + rows=con.execute("select ts,neko_ref,neko_kind,live_page_open,on_air,live_status,health,group_id,substr(studio_url,1,70) from yt_studio_samples where neko_ref like '%ops%1%' or neko_ref='ops:1' or neko_ref='ops-1' order by ts desc limit 8").fetchall() + for r in rows: + d=dict(r); d['age']=round(now-float(d.get('ts') or 0),1); print(d) +except Exception as e: + print('sample_err', e) + print([x[1] for x in con.execute('pragma table_info(yt_studio_samples)')]) +PY + +echo '=== local neko-7 ===' +docker ps -a --format '{{.Names}} {{.Status}}' | grep neko-7 || true +curl -sS -m 2 -o /dev/null -w '9206=%{http_code}\n' http://127.0.0.1:9206/ || true + +echo '=== api relay status snippet (no auth may fail) ===' +# try read journal for gate +journalctl -u douyinweb-api --since '10 min ago' --no-pager 2>/dev/null | grep -iE 'streetfood|neko wait|ops|NODATA|waiting|gate|3fb8|relay' | tail -40 +""" + + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/_why_no_push.sh", "w") as f: + f.write(SCRIPT) + sftp.close() + _i, o, e = c.exec_command("bash /tmp/_why_no_push.sh", timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")[:15000]) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_wipe_dy_rooms.py b/scripts/_wipe_dy_rooms.py new file mode 100644 index 0000000..f0ecd15 --- /dev/null +++ b/scripts/_wipe_dy_rooms.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Wipe rooms on fresh dy.nomadro.live install (no default Douyin rooms).""" +from __future__ import annotations + +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect( + "108.174.50.68", + 22, + "root", + "Xiao4669805", + timeout=45, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + cmd = r""" +cd /opt/douyinWEB/backend +./.venv/bin/python - <<'PY' +import sqlite3 +from pathlib import Path +from app import db + +rooms = db.list_rooms() +print("before", len(rooms)) +for r in rooms: + print("-", r if isinstance(r, str) else (r.get("id"), (r.get("url") or r.get("name") or "")[:80])) + +p = Path("data/monitor.db") +con = sqlite3.connect(str(p)) +tables = [r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()] +print("tables", [t for t in tables if "room" in t.lower() or t in {"settings","kv"}][:40]) +# dump schema-ish +for t in tables: + if "room" in t.lower(): + cols = [x[1] for x in con.execute(f"PRAGMA table_info({t})").fetchall()] + n = con.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] + print("tbl", t, "cols", cols[:12], "n", n) + rows = con.execute(f"SELECT * FROM {t} LIMIT 5").fetchall() + print("sample", rows) + +# Prefer API helpers if present +deleted = 0 +if hasattr(db, "delete_room"): + for r in list(db.list_rooms()): + rid = r if isinstance(r, str) else str((r or {}).get("id") or "") + if rid: + db.delete_room(rid) + deleted += 1 + print("deleted_via_api", deleted) +elif "rooms" in tables: + con.execute("DELETE FROM rooms") + con.commit() + print("deleted_sql_rooms") +else: + # fallback: wipe entire monitor.db and let app recreate empty + con.close() + for f in ("data/monitor.db", "data/monitor.db-shm", "data/monitor.db-wal"): + Path(f).unlink(missing_ok=True) + print("wiped_monitor_db_files") + # reopen app db + rooms2 = db.list_rooms() + print("after_recreate", len(rooms2)) + raise SystemExit(0 if len(rooms2) == 0 else 2) + +con.close() +rooms2 = db.list_rooms() +print("after", len(rooms2)) +print("OK_EMPTY_ROOMS" if len(rooms2) == 0 else "STILL_HAS_ROOMS") +PY +""" + _i, o, e = c.exec_command(cmd, timeout=60) + print((o.read() + e.read()).decode("utf-8", "replace")) + code = o.channel.recv_exit_status() + c.close() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/linux/api_health_watch.sh b/scripts/linux/api_health_watch.sh new file mode 100644 index 0000000..868dd8b --- /dev/null +++ b/scripts/linux/api_health_watch.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Restart douyinweb-api when local /api/health stays down. +# Includes start grace — uvicorn often needs 1–2 minutes before listen. +set +e + +INTERVAL="${DY_API_WATCH_INTERVAL:-20}" +FAILS_NEED="${DY_API_WATCH_FAILS:-4}" +COOLDOWN="${DY_API_WATCH_COOLDOWN:-180}" +GRACE="${DY_API_WATCH_START_GRACE:-180}" +HEALTH_URL="${DY_API_WATCH_URL:-http://127.0.0.1:8014/api/health}" +UNIT="${DY_API_WATCH_UNIT:-douyinweb-api.service}" +RECVQ_LIMIT="${DY_API_WATCH_RECVQ_LIMIT:-200}" + +log() { printf '[api-watch] %s\n' "$*"; } + +fails=0 +last_restart=0 + +recvq_too_high() { + # Listen socket Recv-Q climbing means accept/event-loop wedged even if TCP connects. + local q + q=$(ss -ltn sport = :8014 2>/dev/null | awk 'NR==2 {print $2}') + case "$q" in ''|*[!0-9]*) return 1 ;; esac + [ "$q" -ge "$RECVQ_LIMIT" ] +} + +while true; do + st=$(systemctl is-active "$UNIT" 2>/dev/null || true) + if [ "$st" != "active" ]; then + log "unit=$st skip" + fails=0 + sleep "$INTERVAL" + continue + fi + + started=$(systemctl show -p ActiveEnterTimestamp --value "$UNIT" 2>/dev/null) + if [ -n "$started" ] && [ "$started" != "n/a" ]; then + start_epoch=$(date -d "$started" +%s 2>/dev/null || echo 0) + now_epoch=$(date +%s) + if [ "$start_epoch" -gt 0 ]; then + up=$((now_epoch - start_epoch)) + if [ "$up" -lt "$GRACE" ]; then + log "grace ${up}/${GRACE}s" + fails=0 + sleep "$INTERVAL" + continue + fi + fi + fi + + code=$(curl -sS -m 4 -o /dev/null -w '%{http_code}' "$HEALTH_URL" 2>/dev/null) + [ -n "$code" ] || code=000 + now=$(date +%s) + if [ "$code" = "200" ]; then + if recvq_too_high; then + fails=$((fails + 1)) + log "health=200 but Recv-Q high fails=$fails/$FAILS_NEED" + else + fails=0 + fi + else + fails=$((fails + 1)) + log "health=$code fails=$fails/$FAILS_NEED" + fi + + if [ "$fails" -ge "$FAILS_NEED" ]; then + elapsed=$((now - last_restart)) + if [ "$elapsed" -ge "$COOLDOWN" ]; then + log "restarting $UNIT" + systemctl kill -s SIGKILL "$UNIT" >/dev/null 2>&1 + pkill -9 -f 'uvicorn app.main:app' >/dev/null 2>&1 + sleep 2 + systemctl reset-failed "$UNIT" >/dev/null 2>&1 + systemctl start "$UNIT" >/dev/null 2>&1 + last_restart=$now + fails=0 + else + log "cooldown ${elapsed}/${COOLDOWN}s" + fi + fi + sleep "$INTERVAL" +done diff --git a/scripts/linux/neko_health_watch.sh b/scripts/linux/neko_health_watch.sh new file mode 100644 index 0000000..2566fb9 --- /dev/null +++ b/scripts/linux/neko_health_watch.sh @@ -0,0 +1,239 @@ +#!/usr/bin/env bash +# Soft-heal assign/ops Neko when local HTTP dies. Never wipes profiles/volumes. +# Only: docker restart after consecutive failures + cooldown. +set +e + +INTERVAL="${DY_NEKO_WATCH_INTERVAL:-30}" +FAILS_NEED="${DY_NEKO_WATCH_FAILS:-3}" +COOLDOWN="${DY_NEKO_WATCH_COOLDOWN:-300}" +STATE_DIR="${DY_NEKO_WATCH_STATE_DIR:-/run/douyinweb-neko-watch}" +ASSIGN_MAX="${DY_NEKO_WATCH_ASSIGN_MAX:-8}" +OPS_MAX="${DY_NEKO_WATCH_OPS_MAX:-8}" + +log() { printf '[neko-watch] %s\n' "$*"; } + +mkdir -p "$STATE_DIR" 2>/dev/null || true + +http_ok() { + local port="$1" code + code=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:${port}/" 2>/dev/null) + [ -n "$code" ] || code=000 + case "$code" in + 200|401|403) return 0 ;; + *) return 1 ;; + esac +} + +fail_file() { echo "${STATE_DIR}/${1}.fails"; } +cool_file() { echo "${STATE_DIR}/${1}.last_restart"; } + +bump_fail() { + local key="$1" f n + f="$(fail_file "$key")" + n="$(cat "$f" 2>/dev/null || echo 0)" + case "$n" in ''|*[!0-9]*) n=0 ;; esac + n=$((n + 1)) + echo "$n" >"$f" + echo "$n" +} + +reset_fail() { + echo 0 >"$(fail_file "$1")" +} + +maybe_restart() { + local key="$1" name="$2" fails now last elapsed + fails="$(cat "$(fail_file "$key")" 2>/dev/null || echo 0)" + case "$fails" in ''|*[!0-9]*) fails=0 ;; esac + if [ "$fails" -lt "$FAILS_NEED" ]; then + return 0 + fi + now=$(date +%s) + last="$(cat "$(cool_file "$key")" 2>/dev/null || echo 0)" + case "$last" in ''|*[!0-9]*) last=0 ;; esac + elapsed=$((now - last)) + if [ "$elapsed" -lt "$COOLDOWN" ]; then + log "$name fails=$fails cooldown ${elapsed}/${COOLDOWN}s" + return 0 + fi + if ! docker inspect "$name" >/dev/null 2>&1; then + log "$name missing skip" + reset_fail "$key" + return 0 + fi + running=$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null || echo false) + if [ "$running" != "true" ]; then + log "starting stopped $name" + docker start "$name" >/dev/null 2>&1 + else + log "docker restart $name (http dead, fails=$fails)" + docker restart "$name" >/dev/null 2>&1 + fi + echo "$now" >"$(cool_file "$key")" + reset_fail "$key" +} + +check_one() { + local key="$1" name="$2" port="$3" + if ! docker inspect "$name" >/dev/null 2>&1; then + return 0 + fi + # Soft-start containers killed by OOM (Running=false, OOMKilled=true). Never wipe volumes. + oom=$(docker inspect -f '{{.State.OOMKilled}}' "$name" 2>/dev/null || echo false) + running=$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null || echo false) + if [ "$running" != "true" ] && [ "$oom" = "true" ]; then + n=$(bump_fail "$key") + log "$name OOMKilled fails=$n/$FAILS_NEED" + maybe_restart "$key" "$name" + return 0 + fi + # Only watch containers that exist; if intentionally stopped, skip soft-heal + # unless it was supposed to be running — we only heal Running or Restarting. + state=$(docker inspect -f '{{.State.Status}}' "$name" 2>/dev/null || echo "") + case "$state" in + running|restarting) ;; + *) return 0 ;; + esac + if ! http_ok "$port"; then + n=$(bump_fail "$key") + log "$name :$port down fails=$n/$FAILS_NEED" + maybe_restart "$key" "$name" + return 0 + fi + # HTTP alive but Chrome DevTools dead → still restart (common after SIGILL/OOM-in-chrome). + if ! cdp_ok "$name"; then + n=$(bump_fail "$key") + log "$name CDP:9222 dead (HTTP ok) fails=$n/$FAILS_NEED" + maybe_restart "$key" "$name" + return 0 + fi + # CDP up but renderer Aw Snap / SIGILL (tab title often still "Creator Studio"). + if chrome_crash_ui "$name"; then + n=$(bump_fail "$key") + log "$name Chrome crash UI / SIGILL fails=$n/$FAILS_NEED" + # Prefer soft Chrome restart inside container; fall back to docker restart via maybe_restart. + if soft_restart_chrome "$name"; then + echo "$(date +%s)" >"$(cool_file "$key")" + reset_fail "$key" + return 0 + fi + maybe_restart "$key" "$name" + return 0 + fi + reset_fail "$key" +} + +soft_restart_chrome() { + local name="$1" + docker exec "$name" bash -lc \ + "supervisorctl restart google-chrome 2>/dev/null || supervisorctl restart chromium 2>/dev/null || pkill -TERM -f '/opt/google/chrome/chrome|google-chrome|chromium' 2>/dev/null; echo ok" \ + >/dev/null 2>&1 +} + +chrome_crash_ui() { + local name="$1" out + # Recent SIGILL in chrome log (mtime within 10m). + out=$(docker exec "$name" bash -lc ' + p=/var/log/neko/google-chrome.log + [ -f "$p" ] || exit 1 + # file touched in last 600s? + find "$p" -mmin -10 2>/dev/null | grep -q . || exit 1 + grep -aEi "SIGILL|Illegal instruction|Aw, Snap|STATUS_INVALID" "$p" >/dev/null 2>&1 + ' 2>/dev/null) && return 0 + # Live Studio tab + evaluate timeout / crash text (fast 5s probe). + out=$(docker exec "$name" python3 - <<'PY' 2>/dev/null +import base64,json,os,socket,struct,sys,time,urllib.request +try: + tabs=json.load(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=2)) +except Exception: + sys.exit(1) +pages=[t for t in tabs if t.get("type")=="page"] +pick=None +for t in pages: + u=(t.get("url") or "").lower() + if "studio.youtube.com" in u and "livestreaming" in u: + pick=t; break +if not pick: + sys.exit(1) +ws=pick.get("webSocketDebuggerUrl") or "" +if not ws.startswith("ws://"): + sys.exit(1) +hostport,path=ws[5:].split("/",1); path="/"+path +host,port=hostport.split(":"); port=int(port) +key=base64.b64encode(os.urandom(16)).decode() +try: + s=socket.create_connection((host,port),timeout=3); s.settimeout(3) + s.sendall(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()) + buf=b"" + while b"\r\n\r\n" not in buf: + c=s.recv(2048) + if not c: sys.exit(2) + buf+=c + expr="(document.title||'')+' '+((document.body&&document.body.innerText)||'')[:500]" + data=json.dumps({"id":1,"method":"Runtime.evaluate","params":{"expression":expr,"returnByValue":True}}).encode() + mask=os.urandom(4); h=bytearray([0x81,0x80|len(data)]); h.extend(mask) + s.sendall(bytes(h)+bytes(b^mask[i%4] for i,b in enumerate(data))) + def ex(n): + o=b"" + while len(o) wedged renderer (Aw Snap). + sys.exit(0) +if not text: + sys.exit(0) +low=text.lower() +if "sigill" in low or "aw, snap" in low or "aw snap" in low: + sys.exit(0) +sys.exit(1) +PY +) + [ $? -eq 0 ] +} + +cdp_ok() { + local name="$1" + # DevTools listens inside the container only. + docker exec "$name" curl -fsS -m 2 http://127.0.0.1:9222/json/version >/dev/null 2>&1 && return 0 + docker exec "$name" wget -q -T 2 -O /dev/null http://127.0.0.1:9222/json/version >/dev/null 2>&1 && return 0 + return 1 +} + +log "interval=${INTERVAL}s fails=${FAILS_NEED} cooldown=${COOLDOWN}s assign=1..${ASSIGN_MAX} ops=1..${OPS_MAX}" + +while true; do + if ! command -v docker >/dev/null 2>&1; then + log "no docker" + sleep "$INTERVAL" + continue + fi + i=1 + while [ "$i" -le "$ASSIGN_MAX" ]; do + check_one "assign-$i" "douyinweb-neko-$i" $((9200 + i - 1)) + i=$((i + 1)) + done + i=1 + while [ "$i" -le "$OPS_MAX" ]; do + check_one "ops-$i" "douyinweb-ops-neko-$i" $((18200 + i - 1)) + i=$((i + 1)) + done + sleep "$INTERVAL" +done diff --git a/scripts/linux/shellcrash_tuic_guard.py b/scripts/linux/shellcrash_tuic_guard.py new file mode 100644 index 0000000..2d72f71 --- /dev/null +++ b/scripts/linux/shellcrash_tuic_guard.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Soft-guard: revert Clash selector off VLESS → TUIC. No DB/business changes.""" +from __future__ import annotations + +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +CONTROLLER = os.environ.get("DY_SHELLCRASH_CONTROLLER", "http://127.0.0.1:9999").rstrip("/") +DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_tuic5") +ALLOW_VLESS = str(os.environ.get("DY_SHELLCRASH_ALLOW_VLESS", "") or "").strip().lower() in { + "1", + "true", + "yes", + "on", +} +INTERVAL = int(os.environ.get("DY_SHELLCRASH_GUARD_INTERVAL", "60") or "60") +COOLDOWN = int(os.environ.get("DY_SHELLCRASH_GUARD_COOLDOWN", "120") or "120") +STATE_DIR = os.environ.get("DY_SHELLCRASH_GUARD_STATE", "/run/douyinweb-shellcrash-guard") +_last_fix = 0.0 + + +def log(msg: str) -> None: + print(f"[sc-tuic-guard] {msg}", flush=True) + + +def _http_json(url: str, *, method: str = "GET", body: dict | None = None, timeout: float = 4.0) -> dict: + data = None + headers = {} + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + raw = r.read().decode("utf-8", "replace") + return {"ok": True, "data": json.loads(raw) if raw else {}} + except Exception as exc: + return {"ok": False, "error": str(exc)} + + +def _is_vless(name: str) -> bool: + return "vless" in str(name or "").lower() + + +def _selector_now(proxies: dict) -> tuple[str | None, str | None]: + prefer_keys = ("🚀 节点选择", "GLOBAL", "PROXY", "节点选择") + for key in prefer_keys: + cur = (proxies.get(key) or {}).get("now") + if cur: + return key, str(cur) + for key, val in proxies.items(): + if not isinstance(val, dict) or val.get("type") != "Selector": + continue + cur = val.get("now") + if cur and ("节点" in key or "Select" in key or key.upper() == "PROXY"): + return key, str(cur) + for key, val in proxies.items(): + if isinstance(val, dict) and val.get("type") == "Selector" and val.get("now"): + return key, str(val.get("now")) + return None, None + + +def _select(node: str, proxies: dict) -> None: + groups = [] + for key in ("🚀 节点选择", "GLOBAL", "PROXY"): + if key == "GLOBAL" or key in proxies: + groups.append(key) + for key, val in proxies.items(): + if isinstance(val, dict) and val.get("type") == "Selector" and "节点" in key and key not in groups: + groups.append(key) + if not groups: + groups = ["GLOBAL"] + for g in groups: + enc = urllib.parse.quote(g, safe="") + _http_json(f"{CONTROLLER}/proxies/{enc}", method="PUT", body={"name": node}, timeout=4.0) + + +def guard_once() -> None: + global _last_fix + if ALLOW_VLESS: + return + listed = _http_json(f"{CONTROLLER}/proxies", timeout=4.0) + if not listed.get("ok"): + return + proxies = (listed.get("data") or {}).get("proxies") or {} + group, now = _selector_now(proxies) + if not now or not _is_vless(now): + return + now_ts = time.time() + if now_ts - _last_fix < COOLDOWN: + log(f"VLESS selected ({now}) cooldown skip") + return + log(f"VLESS selected ({group}={now}) -> revert to {DEFAULT_NODE}") + _select(DEFAULT_NODE, proxies) + _last_fix = now_ts + try: + os.makedirs(STATE_DIR, exist_ok=True) + with open(os.path.join(STATE_DIR, "fixes.log"), "a", encoding="utf-8") as f: + f.write(f"{int(now_ts)} {now} -> {DEFAULT_NODE}\n") + except Exception: + pass + + +def main() -> int: + once = len(sys.argv) > 1 and sys.argv[1] == "once" + if once: + guard_once() + return 0 + log(f"interval={INTERVAL}s default={DEFAULT_NODE} allow_vless={int(ALLOW_VLESS)}") + while True: + try: + guard_once() + except Exception as exc: + log(f"WARN {exc}") + time.sleep(max(5, INTERVAL)) + + +if __name__ == "__main__": + raise SystemExit(main() or 0) diff --git a/scripts/linux/shellcrash_tuic_guard.sh b/scripts/linux/shellcrash_tuic_guard.sh new file mode 100644 index 0000000..f348348 --- /dev/null +++ b/scripts/linux/shellcrash_tuic_guard.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# Soft-guard: if Clash selector is on VLESS and VLESS autopick is disabled, +# switch back to DY_SHELLCRASH_DEFAULT_NODE (TUIC). Does not touch DB/business. +# Never rewrites YAML; only PUT /proxies/{group} name=. +set +e + +INTERVAL="${DY_SHELLCRASH_GUARD_INTERVAL:-60}" +COOLDOWN="${DY_SHELLCRASH_GUARD_COOLDOWN:-120}" +CONTROLLER="${DY_SHELLCRASH_CONTROLLER:-http://127.0.0.1:9999}" +DEFAULT_NODE="${DY_SHELLCRASH_DEFAULT_NODE:-1d2da142-singbox_tuic5}" +ALLOW_VLESS="${DY_SHELLCRASH_ALLOW_VLESS:-}" +STATE_DIR="${DY_SHELLCRASH_GUARD_STATE:-/run/douyinweb-shellcrash-guard}" +LAST_FIX=0 + +log() { printf '[sc-tuic-guard] %s\n' "$*"; } + +mkdir -p "$STATE_DIR" 2>/dev/null || true + +allow_vless() { + case "$(printf '%s' "$ALLOW_VLESS" | tr 'A-Z' 'a-z')" in + 1|true|yes|on) return 0 ;; + *) return 1 ;; + esac +} + +is_vless() { + printf '%s' "$1" | grep -qi 'vless' +} + +now_node() { + curl -sS -m 4 "$CONTROLLER/proxies" 2>/dev/null | python3 -c ' +import sys,json +try: + d=json.load(sys.stdin) +except Exception: + sys.exit(1) +ps=d.get("proxies") or {} +for g in ("\u🚀 节点选择".replace("\u",""),): + pass +# Prefer rocket selector, then GLOBAL / PROXY / plain 节点选择 +cands=[] +for k,v in ps.items(): + if isinstance(v,dict) and v.get("type")=="Selector" and v.get("now"): + cands.append((k,v.get("now"))) +for prefer in ("GLOBAL","PROXY","节点选择"): + for k,n in cands: + if prefer in k or k==prefer: + print(n); sys.exit(0) +for k,n in cands: + if "节点" in k or "Select" in k or "PROXY" in k.upper(): + print(n); sys.exit(0) +if cands: + print(cands[0][1]); sys.exit(0) +sys.exit(2) +' 2>/dev/null +} + +select_node() { + local node="$1" + python3 - "$CONTROLLER" "$node" <<'PY' +import json, sys, urllib.parse, urllib.request +ctrl, node = sys.argv[1], sys.argv[2] +try: + with urllib.request.urlopen(ctrl + "/proxies", timeout=4) as r: + ps = json.load(r).get("proxies") or {} +except Exception: + sys.exit(0) +groups = [] +for k, v in ps.items(): + if isinstance(v, dict) and v.get("type") == "Selector": + if k in ("GLOBAL", "PROXY") or "节点" in k or "Select" in k: + groups.append(k) +if not groups: + groups = ["GLOBAL"] +for g in groups: + enc = urllib.parse.quote(g, safe="") + req = urllib.request.Request( + ctrl + "/proxies/" + enc, + data=json.dumps({"name": node}).encode(), + method="PUT", + headers={"Content-Type": "application/json"}, + ) + try: + urllib.request.urlopen(req, timeout=4) + except Exception: + pass +PY +} + +guard_once() { + if allow_vless; then + return 0 + fi + local now + now=$(now_node) || return 0 + if ! is_vless "$now"; then + return 0 + fi + local ts + ts=$(date +%s) + if [ $((ts - LAST_FIX)) -lt "$COOLDOWN" ]; then + log "VLESS selected ($now) but cooldown; skip" + return 0 + fi + log "VLESS selected ($now) -> revert to $DEFAULT_NODE" + select_node "$DEFAULT_NODE" + LAST_FIX=$ts + echo "$ts $now -> $DEFAULT_NODE" >>"$STATE_DIR/fixes.log" 2>/dev/null || true +} + +if [ "${1:-}" = "once" ]; then + guard_once + exit 0 +fi + +log "interval=${INTERVAL}s default=${DEFAULT_NODE} allow_vless=${ALLOW_VLESS:-0}" +while true; do + guard_once || true + sleep "$INTERVAL" || sleep 60 +done diff --git a/scripts/linux/wireguard_watch.sh b/scripts/linux/wireguard_watch.sh index f154783..f474e63 100644 --- a/scripts/linux/wireguard_watch.sh +++ b/scripts/linux/wireguard_watch.sh @@ -1,7 +1,10 @@ #!/usr/bin/env bash # Aggressive WireGuard keepalive watchdog for physical guest (wg-dy / wg-dy-cn). # Handshake alone is not enough — also probe peer reachability and bounce fast. -set -euo pipefail +# +# IMPORTANT: never use `set -e` in the main loop — a single wg/ping failure used +# to exit the unit into activating/crash-loop, leaving tunnels stale for hours. +set +u STATE_DIR="${WIREGUARD_WATCH_STATE_DIR:-/run}" WIREGUARD_WATCH_INTERVAL="${WIREGUARD_WATCH_INTERVAL:-15}" @@ -192,12 +195,12 @@ watch_once() { normalize if [ "${1:-}" = "once" ]; then - watch_once + watch_once || true exit 0 fi log "interval=${WIREGUARD_WATCH_INTERVAL}s stale=${WIREGUARD_STALE_SECONDS}s cooldown=${WIREGUARD_RESTART_COOLDOWN}s ifaces=${WIREGUARD_WATCH_IFACES}" while true; do - watch_once || true - sleep "$WIREGUARD_WATCH_INTERVAL" + watch_once || log "WARN watch_once exited non-zero (continuing)" + sleep "$WIREGUARD_WATCH_INTERVAL" || sleep 15 done