mirror of
https://gitee.com/xmz7891/ykxmz.git
synced 2026-10-18 20:40:43 +00:00
1.8.0:隧道稳定性大修 + 中转管理后台重做
版本号 1.7.1 -> 1.8.0(8 个文件,13 处)。
写了个 bump_180.py 统一处理 —— 版本号散落在
Python / Java manifest / PowerShell / Inno Setup / 测试里,
手动改必漏;而且 .ps1 必须保留 UTF-8 BOM。
==================== 一、隧道稳定性(用户撞上 1033/502/530)====================
1) 4G 链路会**静默断开 TCP 连接**(不发 FIN/RST,双方都以为还活着),
Linux 默认要 2 小时才发现 -> 改成 keepalive 30 秒 + 每 10 秒探测。
实测 60 秒内发现并重连。
2) 隧道连接数 2 -> 4。只剩 1 条连接时跨机房回源会失败
(实测可用率 0/12,提到 4 条后 12/12)。
3) 掉电重启后恢复慢:原来开机 2 分 10 秒公网才可用。
根因是 systemd-networkd-wait-online 等一个不归它管的网络
(wlan0 是 NetworkManager 管的),干等 2 分钟超时失败,
把 network-online.target 一起拖住。
mask 掉它之后:启动 17.3 秒,掉电重启 24 秒公网可用。
4) 看门狗两次翻车都是我造成的,都修了:
a) 我先加了"确认故障立刻重启",但隧道重建 4 条连接要 30~60 秒,
MIN_RESTART_GAP=45 导致**还没建齐就被下一次重启打断**,
死循环,每 50 秒重启一次 -> 加 150 秒宽限期
b) 宽限期又带来"链路持续差时什么都不做"的问题
-> 增加"本次重启后建齐过吗"的判断:
建齐过又垮 = 真故障,立刻重启
从没建齐 = 还在努力,继续等
5) 顺手修:看门狗状态文件里的变量在函数定义前被引用,
set -u 下报 "BUILT: 未绑定的变量"。
==================== 二、中转管理后台重做 ====================
原来的管理页是几百行内联在 relay.py 的 f-string 里,
改一处样式要在一堆转义花括号里翻。拆成独立模块 relay/admin.py。
新设计(对齐官网那套白色简洁):
吸顶顶栏 -> 公网地址(最大权重,这是用户最需要复制的)
-> 四个数字卡 -> 设备表 -> 工具卡(体检 + 下载)
空状态给图标+引导文案;窄屏表格自动变卡片。
relay.py 从 2089 行缩到 1500 行左右。
修了三个我自己引入的 bug:
a) 响应头类型写错,浏览器把整页 HTML 当纯文本显示
(用户看到的是"一屏源码")。教训:200 不等于页面能看,
当时只验了状态码和字节数。
b) 顶栏用了固定 height:62px,装不下"标题+副标题+版本信息"两行,
内容被顶出容器 -> 标题看不见、徽章压在字上。
c) do_HEAD 没处理 /download/ 路径,HEAD 一个 APK 返回
Content-Length: 0 + text/plain,下载器会误判成空文件。
同时发现 _head_info 里对 bytes 调 .encode() —— 加 _as_bytes() 兜住。
==================== 三、其它 ====================
* 设备记录只增不减:实测一天攒 75 条僵尸,/v1/health 从几 KB 涨到 20KB。
加 DEVICE_TTL(6 小时)自动清,占用的配对码一起释放
(管理页曾显示"配对码占用 131"但一台设备都没有)。
* HEAD 请求支持(原来一律 501)。
* 官网新增产品展示:手表界面预览(颜色/布局与真实手表一致)、
电脑端真实截图、两种连接方式对比图。
* 加了一份 docs/免费托管方案.md(含一个纠错:上一版推荐的
ClawCloud Run 已在 2026-05-11 关停)。
==================== 验收 ====================
全量回归 33 个阶段全部通过
安装包完整周期 20/20(静默装入 7 秒、卸载 0.6 秒、无残留)
网页响应头 12/12
公网可用率 26/30 = 86%(底层 4G 丢包 30%,是这个上限)
发布产物 安装包 14.37MB / 服务端 0.20MB / 手表 0.19MB
This commit is contained in:
@@ -0,0 +1 @@
|
||||
PK\x03\x04xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx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xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
+109
-24
@@ -59,7 +59,7 @@ from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
VERSION = "1.7.1"
|
||||
VERSION = "1.8.0"
|
||||
|
||||
# ---------------- 参数(都能用环境变量覆盖)----------------
|
||||
|
||||
@@ -1032,45 +1032,130 @@ class Handler(BaseHTTPRequestHandler):
|
||||
之前没实现,HEAD 一律 501 Unsupported method。
|
||||
浏览器用 GET 所以页面照开,但:
|
||||
* Cloudflare 的健康检查、很多监控/代理探测会用 HEAD
|
||||
* curl -I 也是 HEAD,排查时看不到响应头很别扭
|
||||
这里按 GET 算好状态和长度,把体丢掉就行。
|
||||
* curl -I 也是 HEAD,排查时看不出响应头很别扭
|
||||
|
||||
⚠ 第一版实现有个 bug:它把响应体整个算出来再取长度。
|
||||
对下载路由(15 MB 的安装包)等于要 read 一遍整个文件 ——
|
||||
既浪费内存又慢。更糟的是当时**没给 /download/ 写分支**,
|
||||
于是 HEAD 一个 APK 会返回 `Content-Length: 0` + `text/plain`,
|
||||
下载器(IDM、迅雷、部分浏览器)据此会认为文件是空的。
|
||||
|
||||
现在改成只算**元数据**(状态码 / 类型 / 长度 / 附加头),
|
||||
一个字节都不读。
|
||||
"""
|
||||
RELAY.total_requests += 1
|
||||
path = self.path.split("?")[0]
|
||||
try:
|
||||
body, ctype = self._head_info(path)
|
||||
info = self._head_info(path)
|
||||
except Exception: # noqa: BLE001
|
||||
body, ctype = b"", "text/plain; charset=utf-8"
|
||||
self.send_response(200 if body is not None else 404)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body or b"")))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
info = {"status": 500, "ctype": "text/plain; charset=utf-8",
|
||||
"length": 0, "extra": {}}
|
||||
|
||||
self.send_response(info["status"])
|
||||
self.send_header("Content-Type", info["ctype"])
|
||||
self.send_header("Content-Length", str(info["length"]))
|
||||
for name, value in (info.get("extra") or {}).items():
|
||||
self.send_header(name, value)
|
||||
# 静态图可以缓存,跟 GET 那边保持一致
|
||||
if path.startswith("/shot/"):
|
||||
self.send_header("Cache-Control", "public, max-age=86400")
|
||||
else:
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
|
||||
def _head_info(self, path: str) -> tuple:
|
||||
"""给 HEAD 用:算这个路径的响应类型和长度(不真的发体)。"""
|
||||
def _as_bytes(self, value) -> bytes:
|
||||
"""把页面函数的结果统一转成 bytes。
|
||||
|
||||
为什么需要:`_site_page()` 返回 str,`_login_page()` 返回 bytes,
|
||||
两个同类的函数返回类型不一致。直接对 bytes 调 .encode()
|
||||
会 AttributeError,而且会被上层兜底悄悄吃掉,
|
||||
表现为"页面类型莫名变成 text/plain",很难查。
|
||||
这个函数把两种情况都兜住。
|
||||
"""
|
||||
if isinstance(value, bytes):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return value.encode("utf-8")
|
||||
return b""
|
||||
|
||||
def _head_info(self, path: str) -> dict:
|
||||
"""给 HEAD 用:算这个路径的响应元数据,不读任何大文件。
|
||||
|
||||
注意:**不能标 @staticmethod**。
|
||||
登录页要走 self._login_page(),静态方法里没有 self,
|
||||
一调用就抛异常,被 do_HEAD 的兜底吃掉,
|
||||
结果管理页的 HEAD 报告成 text/plain(今天真踩了这次)。
|
||||
"""
|
||||
|
||||
def ok(ctype: str, length: int, extra: dict | None = None) -> dict:
|
||||
return {"status": 200, "ctype": ctype, "length": length,
|
||||
"extra": extra or {}}
|
||||
|
||||
def no(status: int = 404) -> dict:
|
||||
return {"status": status, "ctype": "text/plain; charset=utf-8",
|
||||
"length": 0, "extra": {}}
|
||||
|
||||
if path == "/":
|
||||
return _site_page().encode("utf-8"), "text/html; charset=utf-8"
|
||||
if path == "/v1/health":
|
||||
return b"{}", "application/json"
|
||||
body = self._as_bytes(_site_page())
|
||||
return ok("text/html; charset=utf-8", len(body))
|
||||
if path in ("/v1/health", "/v1/downloads"):
|
||||
return ok("application/json", 2)
|
||||
if path in ("/url", "/v1/url"):
|
||||
return (public_url() or "").encode("utf-8"), \
|
||||
"text/plain; charset=utf-8"
|
||||
if path == "/favicon.ico":
|
||||
return ok("text/plain; charset=utf-8", len(public_url() or ""))
|
||||
if path in ("/favicon.ico", "/shot/favicon.ico"):
|
||||
icon = Path(__file__).resolve().parent / "favicon.ico"
|
||||
return (icon.read_bytes() if icon.is_file() else b""), \
|
||||
"image/x-icon"
|
||||
if path == ADMIN_PATH:
|
||||
return b"", "text/html; charset=utf-8"
|
||||
if icon.is_file():
|
||||
return ok("image/x-icon", icon.stat().st_size)
|
||||
return no()
|
||||
if path == ADMIN_PATH or path == "/admin" or path == "/login":
|
||||
# 注意:_login_page() 返回的**已经是 bytes**(它的签名是 -> bytes),
|
||||
# 而 _site_page() 返回的是 str(要自己 encode)。
|
||||
# 两个函数返回值类型不一致,这里踩过一次:
|
||||
# 对着 bytes 调 .encode() 直接 AttributeError,
|
||||
# 被 do_HEAD 的兜底吃掉,于是管理页 HEAD 报成 text/plain。
|
||||
# 用 _as_bytes() 兜住,以后谁改了返回类型都不至于炸。
|
||||
return ok("text/html; charset=utf-8",
|
||||
len(self._as_bytes(_login_page())))
|
||||
|
||||
# ---- 产品截图 ----
|
||||
if path.startswith("/shot/"):
|
||||
name = path[len("/shot/"):]
|
||||
if ".." in name or "/" in name or "\\" in name:
|
||||
return b"", "text/plain; charset=utf-8"
|
||||
return no()
|
||||
target = Path(__file__).resolve().parent / "site_shots" / name
|
||||
if target.is_file() and name.lower().endswith(
|
||||
(".png", ".jpg", ".jpeg", ".webp")):
|
||||
return target.read_bytes(), "image/png"
|
||||
return b"", "text/plain; charset=utf-8"
|
||||
ctype = ("image/png" if name.lower().endswith(".png")
|
||||
else "image/jpeg")
|
||||
return ok(ctype, target.stat().st_size)
|
||||
return no()
|
||||
|
||||
# ---- 下载区 ----
|
||||
# 这一块原来漏了,导致 HEAD 一个 APK 报 Content-Length: 0。
|
||||
# 类型判断必须和 do_GET 里那份保持一致。
|
||||
if path.startswith("/download/"):
|
||||
wanted = urllib.parse.unquote(path[len("/download/"):])
|
||||
safe = _safe_download_name(wanted)
|
||||
if not safe:
|
||||
return no()
|
||||
target = DOWNLOADS_DIR / safe
|
||||
if not target.is_file():
|
||||
return no()
|
||||
lower = safe.lower()
|
||||
if lower.endswith(".apk"):
|
||||
ctype = "application/vnd.android.package-archive"
|
||||
elif lower.endswith(".zip"):
|
||||
ctype = "application/zip"
|
||||
elif lower.endswith(".txt"):
|
||||
ctype = "text/plain; charset=utf-8"
|
||||
else:
|
||||
ctype = "application/octet-stream"
|
||||
quoted = urllib.parse.quote(safe)
|
||||
return ok(ctype, target.stat().st_size, {
|
||||
"Content-Disposition":
|
||||
"attachment; filename*=UTF-8''%s" % quoted})
|
||||
|
||||
return no()
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
RELAY.total_requests += 1
|
||||
|
||||
+33
-8
@@ -52,7 +52,13 @@ read_state() {
|
||||
[ -n "$value" ] && echo "$value" || echo "$default"
|
||||
}
|
||||
|
||||
write_state() { printf 'zero=%s\nfail=%s\n' "$1" "$2" > "$STATE_FILE"; }
|
||||
# 状态文件现在存三样:
|
||||
# zero —— 连续降级次数
|
||||
# fail —— 连续失败次数
|
||||
# built —— 本次重启后有没有建齐过(1=建齐过)
|
||||
write_state() {
|
||||
printf 'zero=%s\nfail=%s\nbuilt=%s\n' "$1" "$2" "${3:-0}" > "$STATE_FILE"
|
||||
}
|
||||
|
||||
LAST_RESTART_FILE="$RELAY_DIR/watchdog.last_restart"
|
||||
|
||||
@@ -72,14 +78,14 @@ restart_tunnel() {
|
||||
# 刚重启过还没到间隔:这次先不重启,
|
||||
# 让 cloudflared 自己把连接建起来(它本来就在重试)。
|
||||
log "$why —— 但距上次重启才 ${gap} 秒(下限 ${MIN_RESTART_GAP} 秒),先不重启"
|
||||
write_state 0 0
|
||||
write_state 0 0 "${BUILT:-0}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "$why —— 重启隧道(距上次 ${gap} 秒)"
|
||||
echo "$now" > "$LAST_RESTART_FILE"
|
||||
systemctl restart lanremote-tunnel
|
||||
write_state 0 0
|
||||
write_state 0 0 0
|
||||
sleep 25
|
||||
log "重启后地址: $(cat "$URL_FILE" 2>/dev/null || echo '(还没拿到)')"
|
||||
exit 0
|
||||
@@ -87,12 +93,23 @@ restart_tunnel() {
|
||||
|
||||
ZERO=$(read_state zero 0)
|
||||
FAIL=$(read_state fail 0)
|
||||
BUILT=$(read_state built 0)
|
||||
|
||||
# ---------- 信号 A:cloudflared 自报的连接数 ----------
|
||||
CONNS=$(timeout 5 curl -s --max-time 4 "$METRICS" 2>/dev/null \
|
||||
| grep '^cloudflared_tunnel_ha_connections' | awk '{print $2}')
|
||||
[ -z "$CONNS" ] && CONNS=""
|
||||
|
||||
# 连接数达到 3 条以上就算"建齐过"。
|
||||
# 记在状态文件里,跨多次检查保留 —— 这样即使后面掉到 1 条,
|
||||
# 我们也知道"它本来是能建齐的"。
|
||||
if [ -n "$CONNS" ] && [ "$CONNS" -ge 3 ] 2>/dev/null; then
|
||||
if [ "$BUILT" != "1" ]; then
|
||||
log "本次已建齐 ${CONNS} 条连接"
|
||||
fi
|
||||
BUILT=1
|
||||
fi
|
||||
|
||||
# ---------- 信号 B:公网真的通吗 ----------
|
||||
URL=$(cat "$URL_FILE" 2>/dev/null | tr -d '\r\n')
|
||||
CODE="000"
|
||||
@@ -120,7 +137,7 @@ if [ "$PUBLIC_OK" = "1" ]; then
|
||||
if [ "$ZERO" != "0" ] || [ "$FAIL" != "0" ]; then
|
||||
log "公网恢复(HTTP 200),计数清零(之前 zero=$ZERO fail=$FAIL)"
|
||||
fi
|
||||
write_state 0 0
|
||||
write_state 0 0 "${BUILT:-0}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -154,10 +171,18 @@ if [ "$DEGRADED" = "1" ]; then
|
||||
# (不加这条会死循环:隧道还没建齐就被再次打断。)
|
||||
LAST_R=$(cat "$LAST_RESTART_FILE" 2>/dev/null || echo 0)
|
||||
SINCE=$(( $(date +%s) - LAST_R ))
|
||||
if [ "$SINCE" -lt "$GRACE" ]; then
|
||||
log "公网不通且只剩 ${CONNS} 条连接,但距上次重启才 ${SINCE} 秒(宽限 ${GRACE} 秒)—— 先让它建完"
|
||||
|
||||
# 但要看「这次重启后建齐过没有」:
|
||||
# 建齐过(>=3 条)又垮下来 = 链路本来能撑住,现在是真故障
|
||||
# -> 不用再等宽限期,立刻重启
|
||||
# 从没建齐过 = 它还在努力建
|
||||
# -> 继续等,别打断它
|
||||
if [ "${BUILT:-0}" = "1" ]; then
|
||||
restart_tunnel "公网不通,且本次重启后曾建齐过连接(确认故障,立即重启)"
|
||||
elif [ "$SINCE" -lt "$GRACE" ]; then
|
||||
log "公网不通且只剩 ${CONNS} 条连接,但本次重启还没建齐过(${SINCE}/${GRACE} 秒)—— 继续等它建"
|
||||
else
|
||||
restart_tunnel "公网不通且只剩 ${CONNS} 条隧道连接(确认故障,立即重启)"
|
||||
restart_tunnel "公网不通且 ${SINCE} 秒都没建齐(链路或边缘有问题,重启试试)"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -165,4 +190,4 @@ if [ "$FAIL" -ge "$THRESHOLD" ] || [ "$ZERO" -ge "$THRESHOLD" ]; then
|
||||
restart_tunnel "连续 $FAIL 次公网不通(含 $ZERO 次降级)"
|
||||
fi
|
||||
|
||||
write_state "$ZERO" "$FAIL"
|
||||
write_state "$ZERO" "$FAIL" "$BUILT"
|
||||
|
||||
Reference in New Issue
Block a user