# -*- coding: utf-8 -*- """Stop idle Neko instances on overloaded physical guest; keep exclusive winner.""" from __future__ import annotations import sys import time import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") PASS = "4669805" REMOTE = r''' import json, sqlite3, subprocess, os, sys sys.path.insert(0, "/opt/douyinWEB/backend") os.chdir("/opt/douyinWEB/backend") con=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db") con.row_factory=sqlite3.Row print("=== assign groups neko flags ===") rows=list(con.execute( "SELECT id,name,neko_instance_id,neko_enabled,enabled FROM yt_assign_groups ORDER BY neko_instance_id")) for r in rows: print(dict(r)) # exclusive winner from kv if any w="" try: for r in con.execute("SELECT key,value FROM kv_settings WHERE key LIKE '%exclusive%' OR key LIKE '%relay%'"): if "winner" in r["key"] or r["key"] in ("youtube_relay_exclusive_winner","exclusive_winner_group_id"): print("kv", r["key"], r["value"][:120]) except Exception as e: print("kv err", e) # running containers print("=== docker ps neko ===") ps=subprocess.check_output("docker ps --format '{{.Names}}'", shell=True, text=True) running=sorted(x.strip() for x in ps.splitlines() if "neko" in x) print(running) # Keep: instances that are neko_enabled=1; stop the rest that are running. keep=set() for r in rows: if int(r["neko_enabled"] or 0)==1 and int(r["neko_instance_id"] or 0)>0: keep.add(int(r["neko_instance_id"])) print("keep_enabled", sorted(keep)) # If too many enabled, still stop extras beyond 2 to relieve RAM (operator can start later). # Prefer keep enabled ones; if >2 enabled, keep lowest ids among enabled? Better: keep all enabled # but warn. User machine can't run 7 — force stop non-enabled always; if enabled>=3, stop all but first 1 enabled unless exclusive. enabled_ids=sorted(keep) # Also try relay status exclusive via API local try: import urllib.request j=json.loads(urllib.request.urlopen("http://127.0.0.1:8014/api/youtube/relay/status", timeout=8).read()) wid=str(j.get("exclusive_winner_group_id") or "") print("exclusive_winner", wid) if wid: for r in rows: if r["id"]==wid: keep={int(r["neko_instance_id"])} print("keep only winner", keep) except Exception as e: print("relay status", type(e).__name__, e) # Always stop containers not in keep stopped=[] for name in running: # douyinweb-neko-N try: n=int(name.rsplit("-",1)[-1]) except Exception: continue if keep and n not in keep: print("STOP", name) subprocess.run(["docker","stop","-t","8",name], check=False) stopped.append(n) elif not keep: # no enabled flags: stop all but neko-1 as safety? stop all except lowest running pass if not keep: # stop all but the busiest useful: leave none if all disabled; stop 2..N leave 1? # Safer: stop every running neko — operator can start from UI for name in running: print("STOP_ALL(no enabled)", name) subprocess.run(["docker","stop","-t","8",name], check=False) try: stopped.append(int(name.rsplit("-",1)[-1])) except Exception: pass # Persist DB: set neko_enabled=0 for stopped for n in stopped: con.execute("UPDATE yt_assign_groups SET neko_enabled=0, updated_at=? WHERE neko_instance_id=?", (__import__("time").time(), n)) con.commit() print("=== after ===") print(subprocess.check_output("docker ps --format '{{.Names}}\t{{.Status}}' | grep neko | sort || true", shell=True, text=True)) print(subprocess.check_output("free -h | head -2; uptime", shell=True, text=True)) print("DONE stopped", stopped, "kept", sorted(keep)) ''' def main(): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for i in range(8): try: c.connect( "107.173.30.245", 4014, "eric", PASS, timeout=50, banner_timeout=100, allow_agent=False, look_for_keys=False, ) break except Exception as ex: print("ssh", i, type(ex).__name__, flush=True) time.sleep(2) else: raise SystemExit("ssh fail") sftp = c.open_sftp() with sftp.file("/tmp/_neko_stop_idle.py", "w") as f: f.write(REMOTE) sftp.close() _, o, e = c.exec_command( f"echo '{PASS}' | sudo -S -p '' python3 /tmp/_neko_stop_idle.py", timeout=180, ) print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) c.close() if __name__ == "__main__": main()