Files
jwxt/app/multi_line.py
T

669 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
多线路 Session 管理器
背景:
教务系统 3 条入口线路(公网域名 + 2 个内网 IP)是 3 个独立后端,
session(cookie)跨线路不通用。原方案:线路拥堵切换后强刷 session
(OCR 登录,慢)。本模块改为:提前在每条线路上都养好 session,
切换线路时只做本地文件复制(毫秒级),不再临时登录。
功能:
1. 多线路开关(管理端):开启后后台为所有账号在每条线路上预登录
2. 保活线程:定期心跳检查每条线路的 session,过期自动重登
3. 秒切:线路切换时把目标线路的预热 session 原子写入当前生效的
sessions/{username}.json,先换文件再切 URL
4. 用户线路偏好:用户可固定某条线路(auto = 跟随全局智能切换)
5. 选课模式(管理端):开启后暂停非核心后台任务、拦截非核心查询
配置持久化:BASE_DIR / multi_line_config.json
预热 session 文件:sessions/{username}@{线路tag}.json(格式与现有 session 文件一致)
"""
import json
import os
import time
import logging
import tempfile
import threading
import concurrent.futures
from pathlib import Path
from typing import Dict, List, Optional
from app.settings import BASE_URLS, SESSION_DIR, BASE_DIR
from app.school_manager import DEFAULT_SCHOOL_ID, school_urls, school_for_username, session_key, list_schools
logger = logging.getLogger(__name__)
CONFIG_FILE = BASE_DIR / "multi_line_config.json"
# ── 默认配置 ──
DEFAULT_CONFIG = {
"multi_line_enabled": False, # [已废弃] 旧版全局开关,仅用于一次性迁移到 schools
"xk_mode": False, # [已废弃] 旧版全局开关,仅用于一次性迁移到 schools
"user_preferences": {}, # {session_key(jwxt_username): line_tag},"auto" 或缺省=跟随全局
"schools": {}, # {school_id: {"multi_line_enabled": bool, "xk_mode": bool}} 按学校开关
}
# 预热 session 有效则跳过重登的心跳间隔(秒)
KEEPALIVE_INTERVAL = 20 * 60
# 延迟测量间隔(秒):多线路开启期间每分钟测一轮
LATENCY_INTERVAL = 60
# 登录重试次数
PRELOGIN_RETRIES = 5
_config_lock = threading.Lock()
_config: Dict = {}
_latency_cache: Dict[str, Optional[float]] = {} # tag -> 秒(None=不可达)
_latency_lock = threading.Lock()
_latency_ts: float = 0.0 # 上次测量的时间戳
_keepalive_thread: Optional[threading.Thread] = None
_latency_thread: Optional[threading.Thread] = None
_keepalive_stop = threading.Event()
# ══════════════════════════════════════════════════════════
# 线路注册
# ══════════════════════════════════════════════════════════
def line_tag(url: str) -> str:
"""线路标识:取 URL 的 host 部分(如 jwxt.sdmu.edu.cn / 10.224.2.186)"""
from urllib.parse import urlparse
return urlparse(url).netloc or url
def get_lines(school_id=DEFAULT_SCHOOL_ID) -> List[Dict]:
"""所有线路 [{tag, url}]"""
return [{"tag": line_tag(u), "url": u.rstrip('/')} for u in school_urls(school_id)]
def url_by_tag(tag: str, school_id=DEFAULT_SCHOOL_ID) -> Optional[str]:
for u in school_urls(school_id):
if line_tag(u) == tag:
return u.rstrip('/')
return None
# ══════════════════════════════════════════════════════════
# 配置读写(JSON 文件持久化,无数据库迁移)
# ══════════════════════════════════════════════════════════
def _resolve_school(school_id=None) -> str:
"""显式参数优先,其次线程绑定的学校(请求/抢课线程),最后默认学校"""
if school_id:
return str(school_id)
try:
from app.url_manager import current_school_id
return current_school_id() or DEFAULT_SCHOOL_ID
except Exception:
return DEFAULT_SCHOOL_ID
def _migrate_global_flags(cfg: Dict):
"""旧版全局开关一次性迁移为按学校配置:各学校继承迁移时刻的全局值,行为无缝延续"""
if not isinstance(cfg.get("schools"), dict):
cfg["schools"] = {}
legacy_ml = cfg.get("multi_line_enabled")
legacy_xk = cfg.get("xk_mode")
if legacy_ml is None and legacy_xk is None:
return # 已是按学校配置(或全新安装)
try:
from app.school_manager import list_schools
school_ids = [s['id'] for s in list_schools()]
except Exception:
school_ids = [DEFAULT_SCHOOL_ID]
for sid in school_ids:
flags = cfg["schools"].setdefault(sid, {})
if legacy_ml is not None and "multi_line_enabled" not in flags:
flags["multi_line_enabled"] = bool(legacy_ml)
if legacy_xk is not None and "xk_mode" not in flags:
flags["xk_mode"] = bool(legacy_xk)
# 固化迁移结果,防止每次启动重复继承
for key in ("multi_line_enabled", "xk_mode"):
cfg.pop(key, None)
try:
_atomic_write_json(CONFIG_FILE, cfg)
logger.info("[multi_line] 旧版全局开关已迁移为按学校配置")
except Exception as e:
logger.warning(f"[multi_line] 开关迁移写入失败: {e}")
def _load_config() -> Dict:
global _config
with _config_lock:
if _config:
return _config
# 深拷贝默认值,避免嵌套 dict 被 setdefault 污染模块级常量
cfg = json.loads(json.dumps(DEFAULT_CONFIG))
try:
if CONFIG_FILE and CONFIG_FILE.exists():
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
if isinstance(data, dict):
cfg.update(data)
except Exception as e:
logger.warning(f"[multi_line] 配置读取失败,用默认值: {e}")
_migrate_global_flags(cfg)
_config = cfg
return _config
def _save_config():
with _config_lock:
try:
if CONFIG_FILE and _config:
_atomic_write_json(CONFIG_FILE, _config)
except Exception as e:
logger.error(f"[multi_line] 配置保存失败: {e}")
def is_enabled(school_id=None) -> bool:
"""该校是否开启了多线路 Session 预热(school_id 缺省时取线程绑定学校)"""
flags = _load_config().get("schools", {}).get(_resolve_school(school_id)) or {}
return bool(flags.get("multi_line_enabled"))
def is_xk_mode(school_id=None) -> bool:
"""该校是否开启了选课模式(school_id 缺省时取线程绑定学校)"""
flags = _load_config().get("schools", {}).get(_resolve_school(school_id)) or {}
return bool(flags.get("xk_mode"))
def any_enabled() -> bool:
"""是否任一学校开启了多线路预热(决定后台线程是否需要存活)"""
schools = _load_config().get("schools", {})
return any(bool(f.get("multi_line_enabled")) for f in schools.values())
def set_enabled(enabled: bool, school_id=None) -> Dict:
school_id = _resolve_school(school_id)
_load_config()
with _config_lock:
flags = _config.setdefault("schools", {}).setdefault(school_id, {})
flags["multi_line_enabled"] = bool(enabled)
_save_config()
if enabled:
# 只预热该校账号(prelogin_all 内部按 school_id 过滤)
start_background(prelogin=True, prelogin_school=school_id)
elif not any_enabled():
_keepalive_stop.set()
return {"multi_line_enabled": bool(enabled), "school_id": school_id}
def set_xk_mode(enabled: bool, school_id=None):
school_id = _resolve_school(school_id)
_load_config()
with _config_lock:
flags = _config.setdefault("schools", {}).setdefault(school_id, {})
flags["xk_mode"] = bool(enabled)
_save_config()
# ══════════════════════════════════════════════════════════
# 用户线路偏好
# ══════════════════════════════════════════════════════════
def get_user_preference(jwxt_username: str, school_id=None) -> str:
"""返回用户固定线路 tag;'auto' 或未设置 = 跟随全局"""
prefs = _load_config().get("user_preferences", {})
return prefs.get(session_key(jwxt_username, school_id), "auto")
def set_user_preference(jwxt_username: str, tag: str):
with _config_lock:
prefs = _config.setdefault("user_preferences", {})
key = session_key(jwxt_username)
if tag in ("auto", "", None):
prefs.pop(key, None)
else:
prefs[key] = tag
_save_config()
def get_user_line_url(jwxt_username: str, school_id=None) -> Optional[str]:
"""用户固定线路对应的 URL;auto/未设置返回 None(用全局线路)"""
tag = get_user_preference(jwxt_username, school_id)
if tag == "auto":
return None
return url_by_tag(tag, school_id or school_for_username(jwxt_username))
# ══════════════════════════════════════════════════════════
# 预热 session 文件操作
# ══════════════════════════════════════════════════════════
def _line_session_file(username: str, tag: str) -> Path:
return SESSION_DIR / f"{session_key(username)}@{tag}.json"
def _active_session_file(username: str) -> Path:
return SESSION_DIR / f"{session_key(username)}.json"
def _read_session(path: Path) -> Optional[Dict]:
try:
if not path.exists():
return None
data = json.loads(path.read_text(encoding="utf-8"))
if data.get("cookies"):
return data
except Exception:
pass
return None
def _atomic_write_json(path: Path, data: Dict):
"""原子写入,避免抢课线程读到半截文件"""
fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
except Exception:
try:
os.unlink(tmp)
except OSError:
pass
raise
def _is_session_valid_on(url: str, cookies: Dict, timeout: int = 8) -> bool:
"""检查一份 cookie 在指定线路上是否有效(302=跳登录页=过期)"""
import requests
try:
s = requests.Session()
s.cookies.update(cookies)
r = s.get(url.rstrip('/') + "/xtgl/index_initMenu.html",
allow_redirects=False, timeout=timeout)
return r.status_code == 200
except Exception:
return False
# ══════════════════════════════════════════════════════════
# 预登录(预热)
# ══════════════════════════════════════════════════════════
def _promote_if_serving(username: str, tag: str, url: str):
"""
若该线路正是当前"服务"此用户的线路,把刚登录的新 cookie 同步进生效文件。
背景:正方系统同账号重复登录会挤掉旧 session。预热/保活在某条线路上重登时,
如果该线路正在服务用户(auto 且=全局当前线路,或用户固定了该线路),
生效文件里的旧 session 就会被踢掉——必须同步替换,否则用户请求全挂,
且 keepalive 与 SessionManager 会互相踢对方的 session 形成死循环。
"""
pref = get_user_preference(username)
if pref == tag:
serving = True
elif pref in ('auto', '', None):
from app.url_manager import get_global_base_url
serving = (line_tag(get_global_base_url(school_for_username(username))) == tag)
else:
serving = False
if serving:
_swap_active_session(username, tag, url)
logger.info(f"[multi_line] 重登同步生效 session: {username}@{tag}")
def _login_on_line(username: str, password: str, url: str, tag: str,
max_retries: int = PRELOGIN_RETRIES) -> Dict:
"""在指定线路上登录并把 session 存到 {username}@{tag}.json"""
from app.jwxt_login import JWXTLogin
if not password:
return {"username": username, "tag": tag, "success": False,
"message": "无密码(accounts.json 未配置)"}
login = JWXTLogin(base_url=url)
last_err = ""
for attempt in range(1, max_retries + 1):
try:
result = login.login(username, password)
if result.get("success", False) if isinstance(result, dict) else result:
data = {
"cookies": dict(login.session.cookies),
"headers": dict(login.session.headers),
}
_atomic_write_json(_line_session_file(username, tag), data)
_promote_if_serving(username, tag, url)
return {"username": username, "tag": tag, "success": True}
last_err = (result.get("message", "") if isinstance(result, dict) else "") or "登录失败"
except Exception as e:
last_err = str(e)
if attempt < max_retries:
time.sleep(0.5)
login = JWXTLogin(base_url=url)
return {"username": username, "tag": tag, "success": False, "message": last_err}
def prewarm_user(username: str, password: str, force: bool = False,
only_tags: Optional[List[str]] = None, school_id=None) -> List[Dict]:
"""为一个账号在所有线路上预热 session(3 线路并发,线路间互不阻塞)"""
results = []
school_id = school_id or school_for_username(username)
lines = [l for l in get_lines(school_id) if not only_tags or l["tag"] in only_tags]
def _warm(line):
from app.url_manager import push_school, pop_school
push_school(school_id)
try:
url, tag = line["url"], line["tag"]
data = _read_session(_line_session_file(username, tag))
if data and not force and _is_session_valid_on(url, data.get("cookies", {})):
return {"username": username, "tag": tag, "success": True, "skipped": True}
return _login_on_line(username, password, url, tag)
finally:
pop_school()
with concurrent.futures.ThreadPoolExecutor(max_workers=len(lines)) as ex:
futures = [ex.submit(_warm, l) for l in lines]
for fut in concurrent.futures.as_completed(futures):
try:
results.append(fut.result())
except Exception as e:
results.append({"success": False, "message": str(e)})
return results
def prelogin_all(force: bool = False, progress_callback=None,
school_id: Optional[str] = None) -> Dict:
"""
批量预热账号(账号串行限速防风控,单账号的线路间并发)。
school_id 指定学校 → 只预热该校账号(管理端"该校全量预热")
缺省 → 只预热已开启多线路预热的学校的账号
"""
from app.account_manager import AccountManager
accounts = AccountManager.get_all_accounts()
summary = {"total": 0, "ok": 0, "failed": 0, "details": []}
for i, acc in enumerate(accounts, 1):
username = acc.get("jwxt_username") or acc.get("username") or ""
password = acc.get("jwxt_password") or acc.get("password") or ""
if not username:
continue
acc_school = acc.get('school_id') or DEFAULT_SCHOOL_ID
if school_id:
if acc_school != school_id:
continue
elif not is_enabled(acc_school):
continue # 该校未开启多线路预热
summary["total"] += 1
res = prewarm_user(username, password, force=force, school_id=acc_school)
ok = all(r.get("success") for r in res) if res else False
summary["ok" if ok else "failed"] += 1
summary["details"].append({"username": username, "lines": res})
if progress_callback:
try:
progress_callback(summary["total"], summary["total"] + 1, username, ok, res)
except Exception:
pass
time.sleep(0.3) # 账号间限速
logger.info(f"[multi_line] 预热完成: {summary['ok']}/{summary['total']} 成功"
+ (f" (school={school_id})" if school_id else ""))
return summary
# ══════════════════════════════════════════════════════════
# 秒切(换文件代替重登)
# ══════════════════════════════════════════════════════════
def _swap_active_session(username: str, tag: str, url: str) -> bool:
"""把 {username}@{tag}.json 的 cookies 原子写入生效的 {username}.json"""
data = _read_session(_line_session_file(username, tag))
if not data:
return False
headers = data.get("headers") or {}
headers["Referer"] = url + "/xtgl/index_initMenu.html"
data["headers"] = headers
try:
_atomic_write_json(_active_session_file(username), data)
return True
except Exception as e:
logger.error(f"[multi_line] 换文件失败 {username}@{tag}: {e}")
return False
def prewarm_switch(new_url: str, school_id=DEFAULT_SCHOOL_ID) -> Dict:
"""
全局线路切换的秒切入口(由 url_manager.switch_if_needed 在 set_base_url 之前调用):
1. 校验目标线路可用
2. 对每个账号:把目标线路的预热 session 原子写入生效文件
(用户固定了其他线路的跳过,保持其偏好)
多线路未开启(该校)时为 no-op。
"""
if not is_enabled(school_id):
return {"skipped": "disabled"}
tag = line_tag(new_url)
from app.account_manager import AccountManager
accounts = AccountManager.get_all_accounts()
swapped, missing = 0, 0
for acc in accounts:
username = acc.get("jwxt_username") or acc.get("username") or ""
if not username:
continue
if (acc.get('school_id') or DEFAULT_SCHOOL_ID) != school_id:
continue
from app.url_manager import push_school, pop_school
push_school(school_id)
try:
# 用户固定了别的线路 → 不动他的生效文件
pref = get_user_preference(username)
if pref != "auto" and pref != tag:
continue
if _swap_active_session(username, tag, new_url.rstrip('/')):
swapped += 1
else:
missing += 1
finally:
pop_school()
logger.info(f"[multi_line] 秒切到 {tag}: 换文件 {swapped} 个, 缺预热 {missing} 个")
return {"swapped": swapped, "missing": missing, "tag": tag}
def activate_user_line(username: str, tag: str) -> Dict:
"""
用户选择线路:把他生效的 {username}.json 换成目标线路的预热 session。
返回 {'success': bool, 'message': str}
"""
url = url_by_tag(tag, school_for_username(username))
if not url:
return {"success": False, "message": f"未知线路: {tag}"}
if not is_enabled(school_for_username(username)):
return {"success": False, "message": "多线路模式未开启"}
data = _read_session(_line_session_file(username, tag))
if not data:
return {"success": False, "message": "该线路暂无预热 session,请稍后再试或联系管理员预热"}
if not _is_session_valid_on(url, data.get("cookies", {})):
return {"success": False, "message": "该线路预热 session 已失效,正在等待自动补登"}
if _swap_active_session(username, tag, url):
set_user_preference(username, tag)
return {"success": True, "message": f"已切换到线路 {tag}"}
return {"success": False, "message": "切换失败(文件写入错误)"}
# ══════════════════════════════════════════════════════════
# 延迟测量与状态
# ══════════════════════════════════════════════════════════
def refresh_latency():
"""并发测量所有线路延迟,写入缓存"""
global _latency_ts
from app.url_manager import measure_latency
try:
urls = list({u for school in list_schools() for u in school['urls']})
with concurrent.futures.ThreadPoolExecutor(max_workers=len(urls)) as ex:
fut_to_tag = {ex.submit(measure_latency, u): line_tag(u) for u in urls}
for fut in concurrent.futures.as_completed(fut_to_tag, timeout=10):
tag = fut_to_tag[fut]
try:
with _latency_lock:
_latency_cache[tag] = fut.result()
except Exception:
pass
finally:
_latency_ts = time.time() # 即使超时也更新,避免状态页永远"测速中"
def get_latency(tag: str) -> Optional[float]:
with _latency_lock:
return _latency_cache.get(tag)
def _ensure_latency_fresh(max_age: float = 60):
"""缓存超过 max_age 秒则刷新一次。任一学校开启了多线路时由测速线程每 60s 维护,
请求线程不做同步测量(避免阻塞请求最坏 5~6s),只有全部关闭才现场补测。"""
if time.time() - _latency_ts < max_age:
return
if any_enabled():
return
try:
refresh_latency()
except Exception as e:
logger.warning(f"[multi_line] 延迟测量失败: {e}")
def get_status(school_id=DEFAULT_SCHOOL_ID) -> Dict:
"""管理端状态视图"""
# 注意:用全局地址而非 get_base_url()——本函数常在带线程级线路覆盖的
# 请求线程里被调用,get_base_url() 会返回调用者自己的固定线路
from app.url_manager import get_global_base_url
from app.account_manager import AccountManager
# 缓存过期就现场测一轮,避免一直显示"测速中"
_ensure_latency_fresh()
cfg = _load_config()
current = get_global_base_url(school_id)
n_accounts = sum(1 for acc in AccountManager.get_all_accounts()
if (acc.get('school_id') or DEFAULT_SCHOOL_ID) == school_id)
lines = []
for l in get_lines(school_id):
prefix = '' if school_id == DEFAULT_SCHOOL_ID else f'{school_id}__'
warmed = sum(1 for f in SESSION_DIR.glob(f"*@{l['tag']}.json")
if f.name.startswith(prefix) and
(school_id != DEFAULT_SCHOOL_ID or '__' not in f.name.split('@')[0]))
lines.append({
"tag": l["tag"],
"url": l["url"],
"latency": get_latency(l["tag"]),
"is_current": l["url"] == current.rstrip('/'),
"prewarmed": warmed,
})
return {
"multi_line_enabled": is_enabled(school_id),
"xk_mode": is_xk_mode(school_id),
"school_id": school_id,
"current_line": line_tag(current),
"current_url": current,
"accounts": n_accounts,
"lines": lines,
"user_preferences": dict(cfg.get("user_preferences", {})),
}
# ══════════════════════════════════════════════════════════
# 后台线程
# ══════════════════════════════════════════════════════════
def _latency_loop():
"""延迟测量:多线路开启期间每 60 秒测一轮,供管理端/用户端展示与智能切换参考"""
refresh_latency() # 启动先测一轮,别让页面等 20 分钟才见数值
while not _keepalive_stop.is_set():
_keepalive_stop.wait(LATENCY_INTERVAL)
# 所有学校都关闭预热后彻底退出
if not any_enabled():
break
try:
refresh_latency()
except Exception as e:
logger.warning(f"[multi_line] 延迟测量失败: {e}")
def _backfill_active(username: str):
"""
回填生效文件:用户"应服务线路"(固定偏好,或 auto=全局当前线路)的预热
session 有效,但生效文件在该线路上无效(如缺预热被跳过秒切、或旧线路
cookie 残留)→ 用预热文件回填,避免错误配置持续到下一次全局切换。
"""
url = get_user_line_url(username)
if url is None:
from app.url_manager import get_global_base_url
url = get_global_base_url(school_for_username(username))
tag = line_tag(url)
active = _read_session(_active_session_file(username))
if active and _is_session_valid_on(url, active.get("cookies", {})):
return # 生效文件本来就正常
data = _read_session(_line_session_file(username, tag))
if data and _is_session_valid_on(url, data.get("cookies", {})):
_swap_active_session(username, tag, url)
logger.info(f"[multi_line] 回填生效 session: {username}@{tag}")
def _keepalive_loop():
"""保活:定期心跳所有已开启预热学校的线路预热 session,过期的重登"""
logger.info("[multi_line] 保活线程已启动")
while not _keepalive_stop.is_set():
_keepalive_stop.wait(KEEPALIVE_INTERVAL)
if not any_enabled():
break
try:
from app.account_manager import AccountManager
for acc in AccountManager.get_all_accounts():
if _keepalive_stop.is_set() or not any_enabled():
break
username = acc.get("jwxt_username") or acc.get("username") or ""
password = acc.get("jwxt_password") or acc.get("password") or ""
if not username:
continue
acc_school = acc.get('school_id') or DEFAULT_SCHOOL_ID
if not is_enabled(acc_school):
continue # 该校未开启预热,不消耗登录次数
if not password:
# 无密码账号:keepalive 无法补登,仅提示(其生效 session
# 只能靠用户自己的请求级 with_session_retry 自救)
logger.warning(f"[multi_line] 账号 {username} 无密码,跳过保活(无法自动补登)")
continue
# 只补登失效的线路(prewarm_user 内部会先校验,有效则跳过)
try:
from app.url_manager import push_school, pop_school
push_school(acc_school)
prewarm_user(username, password, force=False, school_id=acc_school)
_backfill_active(username)
except Exception as e:
logger.warning(f"[multi_line] 保活 {username} 失败: {e}")
finally:
pop_school()
time.sleep(0.2)
except Exception as e:
logger.error(f"[multi_line] 保活循环异常: {e}")
logger.info("[multi_line] 保活线程已退出")
def start_background(prelogin: bool = False, prelogin_school: Optional[str] = None):
"""启动保活/测速线程;prelogin=True 时先做一轮预热(后台执行不阻塞)
prelogin_school 指定时只预热该校,否则预热所有已开启预热的学校"""
global _keepalive_thread, _latency_thread
# 无条件 clear:处理"关闭后几秒内重新开启"——旧线程可能还活着但已收到停止信号,
# clear 后它们会继续正常工作;若已退出则重新拉起
_keepalive_stop.clear()
if not (_keepalive_thread and _keepalive_thread.is_alive()):
_keepalive_thread = threading.Thread(target=_keepalive_loop, daemon=True, name="multi-line-keepalive")
_keepalive_thread.start()
if not (_latency_thread and _latency_thread.is_alive()):
_latency_thread = threading.Thread(target=_latency_loop, daemon=True, name="multi-line-latency")
_latency_thread.start()
if prelogin:
threading.Thread(target=prelogin_all, kwargs={'school_id': prelogin_school},
daemon=True, name="multi-line-prelogin").start()