186 lines
9.2 KiB
Python
186 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
||
"""接 Redis 之前 / 之后的自查:这一层到底通不通、通到哪一步。
|
||
|
||
python3 scripts/redis_check.py 按当前生效的运行配置走一遍
|
||
python3 scripts/redis_check.py --host 10.0.0.5 --password 'xxx'
|
||
python3 scripts/redis_check.py --url 'redis://:口令@127.0.0.1:6379/0'
|
||
python3 scripts/redis_check.py --strict 没配 Redis 也当失败(多副本部署的闸门)
|
||
|
||
四步探活(连接 -> 读写 -> 计数 -> 分布式锁)用的是界面上「保存前试一下」同一条路
|
||
(:func:`app.cache.test`);连得上之后再多走几步真接进去的功能:缓存读写与 TTL、按前缀
|
||
清理、共享限流计数、分布式锁互斥、失效广播(真的起订阅线程再收一条回来)。
|
||
|
||
不连 MySQL:Redis 这一层不在"连上库之前"的链路上,本系统对它的定位是可选件,
|
||
检查脚本也不该反过来要求先有一个能用的库。口令只说"配了没有",永不打印。
|
||
写进去的键都在 ``<键前缀>:check:`` 下面,跑完自己删干净。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import os
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
|
||
|
||
#: 命令行参数 -> 运行配置项名(先塞进 OA_* 环境变量,再 import app.cache:
|
||
#: 这样整趟检查用的都是这组参数,不会和界面上存过的值混在一起)
|
||
ENV_OF = {
|
||
"url": "OA_REDIS_URL",
|
||
"host": "OA_REDIS_HOST",
|
||
"port": "OA_REDIS_PORT",
|
||
"db": "OA_REDIS_DB",
|
||
"username": "OA_REDIS_USERNAME",
|
||
"password": "OA_REDIS_PASSWORD",
|
||
"prefix": "OA_REDIS_KEY_PREFIX",
|
||
"timeout": "OA_REDIS_TIMEOUT",
|
||
}
|
||
|
||
|
||
def parse_args() -> argparse.Namespace:
|
||
parser = argparse.ArgumentParser(description="Redis 共享缓存/限流/锁/广播自查")
|
||
parser.add_argument("--url", help="连接串,填了就忽略 host/port/db/username/password")
|
||
parser.add_argument("--host", help="地址,不带 redis:// 与端口")
|
||
parser.add_argument("--port", type=int, help="端口,默认 6379")
|
||
parser.add_argument("--db", type=int, help="库号 0-15")
|
||
parser.add_argument("--username", help="ACL 用户名;只有 requirepass 时留空")
|
||
parser.add_argument("--password", help="口令(会出现在进程列表里,介意就用环境变量传)")
|
||
parser.add_argument("--prefix", help="键前缀,默认在现用前缀后面加 -check,免得碰真数据")
|
||
parser.add_argument("--timeout", type=int, help="读写超时(秒)")
|
||
parser.add_argument("--no-bus", action="store_true", help="跳过失效广播这一段(只查连通性时用)")
|
||
parser.add_argument("--strict", action="store_true", help="没配 Redis 也按失败退出(部署脚本当闸门)")
|
||
return parser.parse_args()
|
||
|
||
|
||
class Report:
|
||
"""一行一条的 OK/FAIL,攒着最后给退出码:一次跑完比逐条中断好查。"""
|
||
|
||
def __init__(self) -> None:
|
||
self.failed: list[str] = []
|
||
|
||
def check(self, label: str, got: object, want: object = True, note: str = "") -> bool:
|
||
ok = got == want
|
||
if not ok:
|
||
self.failed.append(label)
|
||
print(f"{'OK ' if ok else 'FAIL'} {label}: {got!r}" + ("" if ok else f" 期望 {want!r}")
|
||
+ (f" {note}" if note else ""))
|
||
return ok
|
||
|
||
def info(self, text: str) -> None:
|
||
print(f" {text}")
|
||
|
||
def done(self, skipped: str = "") -> int:
|
||
if self.failed:
|
||
print(f"\n失败 {len(self.failed)} 项:{'、'.join(self.failed)}")
|
||
print("排查顺序见 docs/redis-integration.md 第 6 节。")
|
||
return 1
|
||
print(f"\n全部通过{('(' + skipped + ')') if skipped else ''}。")
|
||
return 0
|
||
|
||
|
||
def main() -> int:
|
||
args = parse_args()
|
||
for name, env in ENV_OF.items():
|
||
value = getattr(args, name)
|
||
if value not in (None, ""):
|
||
os.environ[env] = str(value)
|
||
if not args.prefix:
|
||
os.environ["OA_REDIS_KEY_PREFIX"] = "unisoa-check"
|
||
os.environ.setdefault("OA_CONFIG_CACHE_SECONDS", "0")
|
||
|
||
from app import cache # noqa: E402 (必须在上面那几个环境变量塞好之后 import)
|
||
|
||
report = Report()
|
||
cfg = cache.config()
|
||
print("-- 生效配置(口令与连接串只说配了没有)")
|
||
report.check("总闸 redis_enabled", bool(cfg["redis_enabled"]), True)
|
||
report.info(f"地址:{cache._endpoint_label(cfg) if cache.configured() else '(未填,整套能力不启用)'}")
|
||
report.info(f"键前缀:{cfg['redis_key_prefix']} 限流走 Redis:{cfg['redis_rate_limit_enabled']}"
|
||
f" 广播走 Redis:{cfg['redis_broadcast_enabled']}")
|
||
|
||
if not cache.configured():
|
||
print("\n地址留空 = 不启用,这是单副本部署的正常状态:外部取数结果、Hub 令牌与权限、字典选项"
|
||
"各进程自己缓存,限流退回查调用留痕表,改了配置最多等一个快照周期(2 秒)跟上。"
|
||
"\n功能一个不少,只是没有多副本下的一致性。")
|
||
return 1 if args.strict else 0
|
||
|
||
print("\n-- 四步探活(与界面上「保存前试一下」同一条路)")
|
||
result = cache.test()
|
||
for step in result.get("steps") or []:
|
||
report.check(f"{step['step']} 通过", bool(step["ok"]), True, str(step.get("value") or ""))
|
||
if not result.get("ok"):
|
||
report.check("探活整体", False, True, str(result.get("message") or ""))
|
||
return report.done()
|
||
|
||
print("\n-- 接进去的几件事(写在 <前缀>:check: 下面,跑完删)")
|
||
probe = cache.key("check", str(time.time_ns()))
|
||
cache.delete_prefix(cache.key("check"))
|
||
report.check("空缓存读到 None", cache.get_json(probe), None)
|
||
report.check("写 JSON", cache.set_json(probe, {"v": 1, "中文": "值"}, 60), True)
|
||
report.check("读回来", cache.get_json(probe), {"v": 1, "中文": "值"})
|
||
ttl = cache.client().ttl(probe)
|
||
report.check("TTL 真的设上了", 0 < ttl <= 80, True, f"剩 {ttl} 秒(含 10% 抖动)")
|
||
for i in range(3):
|
||
cache.set_json(f"{probe}:{i}", {"i": i}, 60)
|
||
report.check("按前缀清理删掉 4 个键", cache.delete_prefix(cache.key("check")), 4)
|
||
report.check("清完读不到了", cache.get_json(f"{probe}:0"), None)
|
||
|
||
bucket = int(time.time() // 60)
|
||
cache.delete(cache.key("ratelimit", "check:limit", bucket)) # 上一遍跑剩的计数会干扰结论
|
||
report.check("限流:限额内五格都放行",
|
||
[cache.allow("check:limit", 5)[0] for _ in range(5)], [True] * 5)
|
||
blocked, used, retry_after = cache.allow("check:limit", 5)
|
||
report.check("限流:第六格挡住", blocked, False, f"已用 {used} 次,建议等 {retry_after} 秒")
|
||
cache.delete(cache.key("ratelimit", "check:limit", bucket))
|
||
|
||
token = cache.try_lock("check", ttl_seconds=10)
|
||
report.check("拿得到分布式锁", bool(token), True)
|
||
report.check("同一把锁再拿拿不到(别的副本进不来)", cache.try_lock("check", ttl_seconds=10), "")
|
||
holder = cache.lock_holder("check")
|
||
report.check("锁被谁占着报得出(主机名:进程号 开头)", holder.startswith(cache.holder_id()), True, holder)
|
||
cache.release_lock("check", token)
|
||
report.check("交还之后为空", cache.lock_holder("check"), "")
|
||
|
||
if args.no_bus:
|
||
return report.done("跳过失效广播")
|
||
print("\n-- 失效广播(真起订阅线程,收自己发的那一条)")
|
||
if not cache.broadcast_enabled():
|
||
print(" redis_broadcast_enabled = false,这段跳过。")
|
||
return report.done("广播被关")
|
||
got: list[object] = []
|
||
cache.watch("check", got.append)
|
||
report.check("订阅线程起来了", cache.start_bus(), True)
|
||
time.sleep(0.5) # 等订阅落到频道上,否则第一条会没人收
|
||
cache.publish("check", "ping")
|
||
deadline = time.time() + 5
|
||
while not got and time.time() < deadline:
|
||
time.sleep(0.05)
|
||
report.check("收到广播", got[:1], ["ping"])
|
||
# 各模块的订阅是在 import 时挂上去的,所以这一段要把应用导进来才看得见;
|
||
# 少挂一个的表现为"界面上改了、这个副本不跟上",而状态页上只有一个频道名,看不出来。
|
||
try:
|
||
import app.main # noqa: F401
|
||
except Exception as exc: # pragma: no cover - 引导配置不全的机器上也能查 Redis
|
||
report.info(f"没能导入整个应用({type(exc).__name__}),跳过订阅清单这一段")
|
||
else:
|
||
topics = set(cache.status_report()["topics"])
|
||
wanted = {"config", "fetch_cache", "hub_perm", "templates"}
|
||
report.check("该订阅的主题都挂上了", sorted(wanted - topics), [], f"现有:{sorted(topics)}")
|
||
cache.stop_bus()
|
||
|
||
print("\n-- 状态与账本")
|
||
summary = cache.status_report()
|
||
secret = str(cfg["redis_password"] or "")
|
||
report.check("对外报的地址里没有口令", (secret in str(summary["endpoint"])) if secret else False, False)
|
||
report.info(f"计数器:{summary['stats']}")
|
||
if summary["last_error"]:
|
||
report.info(f"最近一次错误:{summary['last_error']}")
|
||
report.check("这一趟没出错", summary["stats"]["errors"], 0)
|
||
cache.delete_prefix(cache.key("check"))
|
||
return report.done()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|