iishko-sandbox: E2B exec broker + tunnel supervisor + bot run_code tool
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
# sandbox_sup.py — держит живыми: (1) exec_broker.py (E2B, локально),
|
||||
# (2) reverse-тunnel home->VPS 127.0.0.1:48979 -> local 48971.
|
||||
# Запуск вручную или кроном Hermes (no_agent): python sandbox_sup.py
|
||||
import os, sys, time, json, subprocess, socket, urllib.request
|
||||
|
||||
HOME_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PY311 = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
CMD = r"C:\Windows\System32\cmd.exe"
|
||||
VPS = "root@2.27.98.196"
|
||||
VPS_FWD = "48979:127.0.0.1:48971" # VPS:48979 -> home:48971
|
||||
LOCAL_HEALTH = "http://127.0.0.1:48971/healthz"
|
||||
VPS_HEALTH = "http://127.0.0.1:48979/healthz"
|
||||
SSH_OPTS = ("-o StrictHostKeyChecking=no -o BatchMode=yes -o ServerAliveInterval=30 "
|
||||
"-o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -o ConnectTimeout=15")
|
||||
LOG = os.path.join(HOME_DIR, "sandbox_sup.log")
|
||||
DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
|
||||
|
||||
def _ensure_winhome():
|
||||
# hermes-bash env lacks USERPROFILE -> native ssh.exe can't resolve ~/.ssh (rc 255, silent)
|
||||
if "USERPROFILE" not in os.environ:
|
||||
os.environ["USERPROFILE"] = r"C:\Users\User"
|
||||
os.environ["HOMEDRIVE"] = "C:"
|
||||
os.environ["HOMEPATH"] = r"\Users\User"
|
||||
os.environ["HOME"] = r"C:\Users\User"
|
||||
|
||||
_ensure_winhome()
|
||||
|
||||
def log(msg):
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg}\n")
|
||||
|
||||
def http_ok(url, timeout=4):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return r.status == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def kill_matching(substr):
|
||||
import psutil
|
||||
me = os.getpid()
|
||||
n = 0
|
||||
for p in psutil.process_iter(["pid", "cmdline"]):
|
||||
try:
|
||||
cl = " ".join(p.info["cmdline"] or [])
|
||||
except Exception:
|
||||
continue
|
||||
if substr in cl and p.info["pid"] != me and "sandbox_sup" not in cl:
|
||||
try:
|
||||
p.kill(); n += 1
|
||||
except Exception:
|
||||
pass
|
||||
return n
|
||||
|
||||
def vps_probe(timeout=45):
|
||||
# питфол: нативный python -> ssh.exe напрямую = rc 255 молча; только через cmd.exe.
|
||||
# Без кавычек и %{} в remote-команде: cmd.exe ест %, remote-bash ломается на вложенных кавычках.
|
||||
r = subprocess.run([CMD, "/c",
|
||||
"ssh %s %s curl -s -m 5 %s" % (SSH_OPTS, VPS, VPS_HEALTH)],
|
||||
capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
|
||||
return '"ok": true' in (r.stdout or ""), r
|
||||
|
||||
def spawn_detached_cmd(cmdline):
|
||||
with open(os.path.join(HOME_DIR, "tunnel.log"), "ab") as fh:
|
||||
subprocess.Popen([CMD, "/c", cmdline], cwd=HOME_DIR, stdout=fh,
|
||||
stderr=subprocess.STDOUT, creationflags=DETACHED,
|
||||
stdin=subprocess.DEVNULL, close_fds=True)
|
||||
|
||||
def main():
|
||||
# 1) локальный брокер
|
||||
if http_ok(LOCAL_HEALTH):
|
||||
log("broker ok")
|
||||
else:
|
||||
kill_matching("exec_broker.py")
|
||||
time.sleep(1)
|
||||
spawn([PY311, os.path.join(HOME_DIR, "exec_broker.py")], out="broker.log")
|
||||
time.sleep(6)
|
||||
log("broker " + ("started" if http_ok(LOCAL_HEALTH) else "START FAILED"))
|
||||
|
||||
# 2) reverse-туннель на прод (проверяем с той стороны)
|
||||
ok, _ = vps_probe()
|
||||
if ok:
|
||||
log("tunnel ok")
|
||||
return
|
||||
kill_matching(VPS_FWD)
|
||||
time.sleep(1)
|
||||
spawn_detached_cmd("ssh %s -N -R %s %s" % (SSH_OPTS, VPS_FWD, VPS))
|
||||
time.sleep(8)
|
||||
ok, r = vps_probe()
|
||||
if ok:
|
||||
log("tunnel started")
|
||||
else:
|
||||
log("tunnel START FAILED rc=%s out=%r err=%r" % (r.returncode, r.stdout[:80], r.stderr[:120]))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user