feat: 新增模块化Streamlit本地工具箱
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
"""文件持久化任务记录;任务进程独立于浏览器会话。"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from filelock import FileLock
|
||||
import psutil
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TASKS = ROOT / "output" / "toolbox" / "tasks"
|
||||
ACTIVE = {"queued", "running"}
|
||||
LABELS = {"queued": "启动中", "running": "运行中", "success": "已完成",
|
||||
"failed": "失败", "cancelled": "已停止", "interrupted": "意外中断"}
|
||||
KINDS = {"market": "市场网格出图", "buildings": "楼宇数据查询"}
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
for attempt in range(20):
|
||||
try:
|
||||
temporary.replace(path)
|
||||
break
|
||||
except PermissionError:
|
||||
if attempt == 19:
|
||||
raise
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def alive(state):
|
||||
try:
|
||||
process = psutil.Process(state["pid"])
|
||||
return (abs(process.create_time() - state["process_created"]) < 0.1
|
||||
and process.is_running() and process.status() != psutil.STATUS_ZOMBIE)
|
||||
except (KeyError, ValueError, psutil.Error):
|
||||
return False
|
||||
|
||||
|
||||
def read_task(directory):
|
||||
directory = Path(directory)
|
||||
state = json.loads((directory / "state.json").read_text(encoding="utf-8"))
|
||||
if state["status"] in ACTIVE and not alive(state):
|
||||
if time.time() - state["created"] > 15:
|
||||
# 不写回,避免与刚完成的 worker 原子更新发生竞争。
|
||||
state = {**state, "status": "interrupted", "message": "任务进程已退出,已完成文件保留。"}
|
||||
state["stop_requested"] = (directory / "stop").exists()
|
||||
return state
|
||||
|
||||
|
||||
def list_tasks():
|
||||
if not TASKS.exists():
|
||||
return []
|
||||
return [read_task(p.parent) for p in sorted(TASKS.glob("*/state.json"), reverse=True)]
|
||||
|
||||
|
||||
def start_task(kind, params, credentials=None):
|
||||
from .validation import validate
|
||||
validate(kind, params)
|
||||
TASKS.mkdir(parents=True, exist_ok=True)
|
||||
with FileLock(str(TASKS / ".launch.lock"), timeout=10):
|
||||
if any(t["status"] in ACTIVE for t in list_tasks()):
|
||||
raise ValueError("已有任务正在运行,请等待完成或到任务中心停止它。")
|
||||
task_id = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
|
||||
directory = TASKS / task_id
|
||||
directory.mkdir()
|
||||
output = directory / "results"
|
||||
output.mkdir()
|
||||
state = {"id": task_id, "kind": kind, "status": "queued", "created": time.time(),
|
||||
"output": str(output), "params": params, "done": 0, "total": 0,
|
||||
"message": "正在启动", "directory": str(directory)}
|
||||
write_json(directory / "state.json", state)
|
||||
process = None
|
||||
try:
|
||||
env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}
|
||||
flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
||||
with (directory / "task.log").open("wb") as log:
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-u", "-m", "toolbox.worker", str(directory)],
|
||||
cwd=ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
|
||||
env=env, creationflags=flags,
|
||||
)
|
||||
state.update(pid=process.pid, process_created=psutil.Process(process.pid).create_time())
|
||||
write_json(directory / "state.json", state)
|
||||
# 凭据只经标准输入传给独立任务进程,不写配置文件或命令行。
|
||||
process.stdin.write(json.dumps(credentials or {}).encode("utf-8"))
|
||||
process.stdin.close()
|
||||
threading.Thread(target=process.wait, daemon=True, name=f"wait-{task_id}").start()
|
||||
except Exception:
|
||||
if process is not None:
|
||||
if process.stdin and not process.stdin.closed:
|
||||
process.stdin.close()
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
state.update(status="failed", message="任务进程启动失败", finished=time.time())
|
||||
write_json(directory / "state.json", state)
|
||||
raise
|
||||
return task_id
|
||||
|
||||
|
||||
def stop_task(task_id):
|
||||
directory = TASKS / task_id
|
||||
if read_task(directory)["status"] in ACTIVE:
|
||||
(directory / "stop").touch()
|
||||
|
||||
|
||||
def tail_log(directory, max_bytes=24000):
|
||||
path = Path(directory) / "task.log"
|
||||
if not path.exists():
|
||||
return "等待任务输出……"
|
||||
with path.open("rb") as source:
|
||||
source.seek(max(0, path.stat().st_size - max_bytes))
|
||||
return source.read().decode("utf-8", errors="replace")
|
||||
Reference in New Issue
Block a user