167 lines
7.4 KiB
Python
Executable File
167 lines
7.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""接口为什么这么慢:一次量出"耗时 + 数据库来回数 + 最慢的那几条 SQL"。
|
||
|
||
python3 scripts/slow_reads.py --password 'xxx'
|
||
python3 scripts/slow_reads.py --account localadmin --password 'xxx'
|
||
python3 scripts/slow_reads.py --path /api/v1/portal/home --threshold 200
|
||
echo -n '密码' | python3 scripts/slow_reads.py --password-stdin
|
||
|
||
怎么用这份结果
|
||
==============
|
||
本系统的库通常在另一台机器上,一条 SQL 的往返就要十几二十毫秒,于是**慢下来几乎从来不是
|
||
某条 SQL 写得慢,而是一个接口问了几十次**。所以看第二列比看第三列重要:
|
||
|
||
* ``SQL 次数`` 大 => 少几个来回(合批、``IN`` 一次取完、缓存)。逐行问一次的 N+1 就是这一类;
|
||
* ``SQL 次数`` 小但耗时仍高 => 数据库本身或网络在抖,量一下 ``SELECT 1`` 的往返就分得清;
|
||
* ``SQL 合计`` 远小于总耗时 => 时间没花在数据库上,往后端计算、外部 HTTP 调用那边去找。
|
||
|
||
进程内直接调 ASGI 应用,不额外占端口、不重启服务;只做 ``GET``,一个写接口都不碰。
|
||
口令走命令行会进 shell 历史与进程列表,介意的话用 ``--password-stdin``。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import collections
|
||
import getpass
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
#: 默认探一圈:登录之后界面上第一屏要点的那几个,加两个管理页做对照
|
||
DEFAULT_PATHS = (
|
||
"/api/v1/auth/me",
|
||
"/api/v1/settings/public",
|
||
"/api/v1/notification/unread/count",
|
||
"/api/v1/statistics/workbench",
|
||
"/api/v1/portal/home",
|
||
"/api/v1/org/persons?page=1&size=20",
|
||
"/api/v1/notification?page=1&size=20",
|
||
"/api/v1/system/info",
|
||
)
|
||
|
||
#: 一条语句归一化之后的分组键:数字、绑定参数、IN 列表都换成占位符,同一写法才归到一格
|
||
_SHAPES = ((re.compile(r"#[A-Za-z0-9_]+"), "?"), (re.compile(r":__[A-Za-z0-9_]+"), "?"),
|
||
(re.compile(r"IN \([^)]*\)", re.I), "IN (...)"), (re.compile(r"\s+"), " "))
|
||
|
||
|
||
def shape(sql: str) -> str:
|
||
out = sql.strip()
|
||
for pattern, repl in _SHAPES:
|
||
out = pattern.sub(repl, out)
|
||
return out[:110]
|
||
|
||
|
||
def parse_args() -> argparse.Namespace:
|
||
parser = argparse.ArgumentParser(description="量接口的耗时与数据库来回数")
|
||
parser.add_argument("--account", default="", help="登录账号;默认用配置里的内置超管账号。"
|
||
"Hub 开着时用应急账号(local_only_accounts)能少等十秒")
|
||
parser.add_argument("--password", default="", help="登录口令")
|
||
parser.add_argument("--password-stdin", action="store_true", help="从标准输入读口令,不落进程列表")
|
||
parser.add_argument("--path", action="append", default=[], help="要量的接口,可重复;不给就用默认那一圈")
|
||
parser.add_argument("--rounds", type=int, default=3, help="每个接口跑几轮,取后面几轮的中位数(默认 3)")
|
||
parser.add_argument("--threshold", type=float, default=0.0, help="只报中位数超过这么多毫秒的接口")
|
||
parser.add_argument("--top", type=int, default=3, help="每个接口列出最慢的前几条 SQL")
|
||
return parser.parse_args()
|
||
|
||
|
||
class Meter:
|
||
"""挂在 SQLAlchemy 上数语句:次数、每条花多久,都在同一个来回里量。"""
|
||
|
||
def __init__(self) -> None:
|
||
self.rows: list[tuple[float, str]] = []
|
||
|
||
def install(self) -> None:
|
||
from sqlalchemy import event
|
||
|
||
from app.db import engine
|
||
|
||
@event.listens_for(engine, "before_cursor_execute")
|
||
def _before(conn, cursor, statement, parameters, context, executemany):
|
||
context._slow_reads_started = time.perf_counter()
|
||
|
||
@event.listens_for(engine, "after_cursor_execute")
|
||
def _after(conn, cursor, statement, parameters, context, executemany):
|
||
started = getattr(context, "_slow_reads_started", None)
|
||
if started is not None:
|
||
self.rows.append(((time.perf_counter() - started) * 1000, statement))
|
||
|
||
|
||
def median(values: list[float]) -> float:
|
||
ordered = sorted(values)
|
||
if not ordered:
|
||
return 0.0
|
||
middle = len(ordered) // 2
|
||
return ordered[middle] if len(ordered) % 2 else (ordered[middle - 1] + ordered[middle]) / 2
|
||
|
||
|
||
def main() -> int:
|
||
args = parse_args()
|
||
os.environ.setdefault("OA_SCHEDULER", "off")
|
||
# 量性能不该顺手改表结构:这一趟只读
|
||
os.environ.setdefault("OA_AUTO_CREATE_SCHEMA", "false")
|
||
from starlette.testclient import TestClient
|
||
|
||
from app.config import settings
|
||
from app.main import app
|
||
|
||
password = sys.stdin.read().strip() if args.password_stdin else args.password
|
||
account = args.account or settings.admin_account
|
||
if not password:
|
||
password = getpass.getpass(f"{account} 的口令:")
|
||
|
||
meter = Meter()
|
||
meter.install()
|
||
client = TestClient(app)
|
||
response = client.post("/api/v1/auth/login", json={"account": account, "password": password})
|
||
if response.status_code != 200:
|
||
print(f"登录失败({response.status_code}):{response.text[:200]}")
|
||
print("提示:Hub 开着时超管账号会先等一次 Hub 超时。用应急账号更快,"
|
||
"见运行配置「只走本地口令的账号」(local_only_accounts)。")
|
||
return 1
|
||
headers = {"Authorization": f"Bearer {response.json()['data']['access_token']}"}
|
||
|
||
print(f"\n{'接口':44}{'中位耗时':>9}{'SQL次数':>8}{'SQL合计':>9}")
|
||
slowest: list[tuple[float, str, list[tuple[str, int, float]]]] = []
|
||
for path in (args.path or DEFAULT_PATHS):
|
||
timings, grouped = [], collections.defaultdict(lambda: [0, 0.0])
|
||
for round_index in range(max(1, args.rounds)):
|
||
meter.rows.clear()
|
||
started = time.perf_counter()
|
||
answer = client.get(path, headers=headers)
|
||
elapsed = (time.perf_counter() - started) * 1000
|
||
if round_index: # 第一轮带着连接建立与配置快照,不算数
|
||
timings.append(elapsed)
|
||
for ms, sql in meter.rows:
|
||
bucket = grouped[shape(sql)]
|
||
bucket[0] += 1
|
||
bucket[1] += ms
|
||
middle = median(timings)
|
||
total = sum(value[1] for value in grouped.values())
|
||
top = sorted(grouped.items(), key=lambda item: -item[1][1])[: max(0, args.top)]
|
||
if answer.status_code != 200:
|
||
print(f"{path:44}{'-':>9}{'-':>8}{'-':>9} HTTP {answer.status_code}")
|
||
continue
|
||
if args.threshold and middle < args.threshold:
|
||
continue
|
||
print(f"{path:44}{middle:8.0f} {len(meter.rows):8}{total:9.0f}")
|
||
slowest.append((middle, path, [(key, value[0], value[1]) for key, value in top]))
|
||
|
||
worth = [item for item in slowest if item[2] and sum(row[2] for row in item[2]) > 40]
|
||
if worth:
|
||
print("\n每个接口里最慢的几条 SQL(次数 x 合计毫秒)")
|
||
for _, path, top in worth:
|
||
print(f"\n {path}")
|
||
for key, count, ms in top:
|
||
print(f" {count:>3}x {ms:7.0f} ms {key}")
|
||
print("\n参照:一条 SQL 的往返大约就是数据库那台机器的网络延迟,"
|
||
"先确认 SELECT 1 要多久,再看次数是不是能合批。")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|