fix: save PID from Popen, check alive via os.kill, read link from log file

This commit is contained in:
OpenCode Agent 2026-08-17 22:34:04 +00:00
parent 1a6c956666
commit c3899471e3
1 changed files with 34 additions and 21 deletions

View File

@ -5,7 +5,6 @@ import os
import shutil import shutil
import logging import logging
import time import time
import threading
from typing import Optional from typing import Optional
from fastapi import APIRouter from fastapi import APIRouter
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@ -16,6 +15,7 @@ router = APIRouter()
_sshx_link = None _sshx_link = None
_sshx_pid = None _sshx_pid = None
_sshx_log = "/tmp/sshx_link.log" _sshx_log = "/tmp/sshx_link.log"
_sshx_pid_file = "/tmp/sshx_link.pid"
LINK_RE = re.compile(r"https://sshx\.io/s/[A-Za-z0-9_-]+") LINK_RE = re.compile(r"https://sshx\.io/s/[A-Za-z0-9_-]+")
@ -39,12 +39,13 @@ def _kill_sshx():
if _sshx_pid: if _sshx_pid:
try: try:
os.kill(_sshx_pid, 15) os.kill(_sshx_pid, 15)
except ProcessLookupError: except (ProcessLookupError, PermissionError):
pass pass
_sshx_pid = None _sshx_pid = None
_sshx_link = None _sshx_link = None
if os.path.exists(_sshx_log): for f in [_sshx_log, _sshx_pid_file]:
os.remove(_sshx_log) if os.path.exists(f):
os.remove(f)
def _is_alive() -> bool: def _is_alive() -> bool:
@ -54,37 +55,49 @@ def _is_alive() -> bool:
try: try:
os.kill(_sshx_pid, 0) os.kill(_sshx_pid, 0)
return True return True
except ProcessLookupError: except (ProcessLookupError, PermissionError):
return False return False
def _read_link_from_log() -> Optional[str]:
if not os.path.exists(_sshx_log):
return None
try:
with open(_sshx_log) as f:
content = f.read()
m = LINK_RE.search(content)
if m:
return m.group(0)
except Exception:
pass
return None
def _start_sshx_background(): def _start_sshx_background():
global _sshx_pid, _sshx_link global _sshx_pid, _sshx_link
_kill_sshx() _kill_sshx()
_sshx_link = None _sshx_link = None
subprocess.Popen( log_fh = open(_sshx_log, "w")
["nohup", "sshx", "--quiet"], proc = subprocess.Popen(
stdout=open(_sshx_log, "w"), ["sshx", "--quiet"],
stdout=log_fh,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
start_new_session=True, start_new_session=True,
) )
_sshx_pid = proc.pid
with open(_sshx_pid_file, "w") as pf:
pf.write(str(proc.pid))
for _ in range(30): for _ in range(30):
time.sleep(1) time.sleep(1)
if os.path.exists(_sshx_log) and os.path.getsize(_sshx_log) > 0: link = _read_link_from_log()
with open(_sshx_log) as f: if link:
content = f.read().strip() _sshx_link = link
m = LINK_RE.search(content)
if m:
_sshx_link = m.group(0)
try:
with open("/tmp/sshx_pid") as pf:
_sshx_pid = int(pf.read().strip())
except Exception:
pass
return True return True
if proc.poll() is not None:
return False
return False return False