feat: Python(Locust) + Go(boomer) 混合压测框架(演示版)

This commit is contained in:
WbiubiuW
2026-09-22 14:28:45 +08:00
commit b414d7e320
135 changed files with 6171 additions and 0 deletions
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
bin/
.pids/
__pycache__/
.pytest_cache/
*.pyc
*.log
.DS_Store
+219
View File
@@ -0,0 +1,219 @@
# perf-harness-demo —— Python / Go 混合压测实验台
用一个**可复现的小规模实验台**,验证压测工程里最容易出错的三条判断。
同一个本机 mock 服务,分别用 **Python worker(Locust 原生)** 和 **Go worker(boomer)** 施压,
统计口径统一,产出两者的 TPS / 延迟对比报告。所有数字都由本仓库自己跑出来,随时可复跑。
---
## 先说结论
本仓库跑出来的东西是三张表、三条判断。数字取自 `report.md`(本机单机实测):
| # | 判断 | 怎么验出来的 | 实测 |
|---|---|---|---|
| ① | **工具选型要能被证伪**,不是选"最好的" | 同并发、同场景、同请求体,只换 worker | Go 的 TPS ≈ **Python 的 4 倍**(多次复跑 3.9–4.2×) |
| ② | **压测脚本的失真比被测系统的 bug 更隐蔽** | 条件单触发价「写死」vs「缓存服务实时驱动」 | 写死:**100% / 0%**;缓存驱动:**≈50%**(历次 48–55%)。三组**失败数全为 0** |
| ③ | **瓶颈要定位到"谁不够",而不是"慢"** | 给 mock 设单实例上限,对比 1 / 4 实例 | 1 实例封顶 **≈500 TPS**、P95 200ms → 4 实例 **≈2000 TPS**、P95 ≈50ms(**≈4×**) |
绝对数字随机器与负载波动,以 `report.md` 里的当轮实测为准;**稳定的是倍数差与瓶颈归属**。
②是全篇最值钱的一条:写死触发价的两个相位,**HTTP 全 200、失败数 0、延迟正常** ——
报表上挑不出任何毛病,但触发率塌缩到 0% 和 100%,这批数据对容量评估毫无意义。
「数据是错的,但看起来是对的」。
---
## 这不是什么
先讲清楚,免得被误读:
- **这不是生产系统**,也不是任何线上系统的代码。它是一个**实验台**:把三条工程判断做成可运行、可复跑的最小装置。
- **它不追求压出高 TPS**。本机单机压测的量级(几千 TPS)和生产环境没有可比性 ——
可比的是**同一台机器上的倍数差**和**瓶颈在哪一层**,这才是要证明的东西。
- **只压本机 `127.0.0.1` 的 mock**,不连任何真实服务、绝不对外发压。
---
## 快速开始
**依赖**
| 项 | 版本 | 用于 |
|---|---|---|
| Python | 3.9+ | 全部 |
| [locust](https://locust.io) | 2.x | 压测(Python worker / master) |
| pytest | — | 仅跑单测(单测不依赖 locust) |
| Go | 1.21+ | 编译 Go worker(本机 go1.25 验证通过) |
```bash
python3 -m pip install locust pytest
```
> macOS 上 `python3` 常指向一个没装这些包的解释器。确认一下:
> `python3 -c "import locust, pytest"` 不报错再往下走;否则换成你实际装了依赖的那个解释器
> (本机是 `~/miniconda3/bin/python3`)。
**跑一遍**
```bash
bash run.sh target # 起本机 mock(HTTP :18099)
bash run.sh python --users 50 --duration 60s # 判断①:Python worker
bash run.sh go --users 50 --duration 60s # 判断①:Go worker(master/slave)
python3 scenarios/verify_trigger.py # 判断②:写死 vs 缓存驱动,一次跑完两组
bash run.sh scale-1 # 判断③:1 实例
bash run.sh scale-4 # 判断③:4 实例
bash run.sh report # 汇总 results/*.json → report.md
```
每条压测命令都会往 `results/` 落一份 JSON,报告的数字**只从这些 JSON 里读**,不手写。
**验证**
```bash
python3 -m pytest tests/ -q # 21 passed
(cd go && go test ./...) # Go 侧:连接池断言
```
单测钉住的是最容易做假、且做假了没人看得见的语义:滑动窗口去重(含 A-B-A 交替)、
断流回退、触发判定方向、限流器、分流器、连接池断言。
---
## 架构
```
run.sh python run.sh go
───────────── ──────────
Locust 单进程直跑 Locust master(控制面 + 统计汇总)
(不经 master) │ ZMQ :5557
│ ▼
│ Go worker (boomer slave)
│ goroutine × N
│ │
└──────────────┬──────────────────────┘
│ HTTP /api/v1/order/...(同场景、同请求体)
▼
┌──────────────────────┐
│ HTTP mock :18099│ 条件单 endpoint + TARGET_MAX_QPS 上限
└──────────┬───────────┘
▲ 行情轮询
┌──────────┴───────────┐ ┌────────────────────────┐
│ mark_price_service │ │ dispatcher :18100│
│ :18097 标记价缓存 │ │ 扩展实验的入口分流 │
└──────────────────────┘ └────────────────────────┘
```
两种 worker 的统计都汇到同一个 Locust master,保证**同口径出数**。
任务表是配置驱动的(`python/locustfile.py` 的 `TASK_WEIGHTS`、`go/tasks.go` 的 `taskTable()`),
增删任务不动框架。
---
## 关键技术点
1. **GIL 取舍**:Python 单进程内所有协程共享一个 GIL,JSON 编解码、locust 统计、gevent 调度
都是纯 CPU 段,并发上去单核打满、TPS 触顶。Go 的 goroutine 由 runtime 多线程调度、
网络 I/O 走 netpoller,没有这个天花板。
2. **连接池调优必须落在"真身"上**:手写 `http.Transport` 时,参数很容易落在一个
**从未被 `client.Transport` 引用**的变量上 —— 于是默认的 `MaxIdleConnsPerHost=2` 生效,
压不上去,却极易被误归因到被测服务。`TestTransportPool` **断言 client 实际使用的
transport 就是调优过的那个**,把「我调优了」从错觉变成事实。
3. **标记价缓存的两条硬语义**(`target/mark_price_service.py`,由 `tests/` 钉死):
- **滑动窗口去重**:窗口必须保存最近两个**已接受**的价格。只存"最后一个值"的伪窗口
识别不了 A-B-A 交替重复(100→105→100 时第三笔会被误判为新变化),等于没去重。
- **断流回退**:行情源挂掉时**回退默认价继续出价**,不是报错退出 —— 压测不能中断。
4. **单实例上限要可测量**:mock 支持 `TARGET_MAX_QPS`(超限请求排队等位,表现为 TPS 封顶 +
延迟上升,而**不是**错误率上升)与 `TARGET_EXTRA_LATENCY_MS`。`run.sh scale-N` 起 N 个实例
+ 入口分流器,用**除实例数外完全一致**的参数对比 —— 扩展是有依据的决策,不是"感觉慢了加机器"。
5. **boomer 与 locust 2.x 的协议补丁**(`go/third_party/boomer`,3 处,见
[THIRD_PARTY.md](THIRD_PARTY.md)):`client_ready` data `nil → -1`;`spawn` 消息迁移到
`user_classes_count/parsed_options`;`stats` / `spawning_complete` 上报
`user_classes_count`(否则被当 unknown worker 踢掉)。
---
## 背景:这套东西是怎么来的
> 这一节讲的是**动机**,不是本仓库能提供的证据。下面那些生产数字来自我此前的合约交易系统
> 压测经历,**本仓库不承载、也无法复现它们**;本仓库只复现方法论。
当时的指标是:10 个用户并发下单,下单接口 TPS 达到 10 万。用阶梯压测(1h → 2h → 4/8/12/24h)
验证长期稳定性,而不是测瞬时峰值。过程中撞了三次瓶颈:
| # | 瓶颈 | 破局 |
|---|---|---|
| 1 | 压测脚本自己失真:条件单触发价写死 → 全触发或全不触发,整批数据作废 | 自建标记价格缓存服务:订阅行情 → 滑动窗口去重 → 本地缓存 TTL;**断流时回退默认价**保证压测不中断 |
| 2 | Python GIL:Locust 动态参数灵活,但单机打不满并发 | 用 Go + boomer 重写压力机,Python 只留 Locust master 做控制;另用 gRPC 客户端直压绕过 HTTP 层(**这条 gRPC 通道本仓库没有复刻**) |
| 3 | 单服务集群上限约 12000,撑不起指标 | 横向扩展:委托/结算/权益 40 实例、撮合/风控 10、入口 Nginx 20 |
结果:10 用户并发、平均响应 1-2s、24h 稳定运行、实测 10-12 万 TPS。
**工具选型的试错路径**(JMeter → Locust → Go + boomer):
| 方案 | 为什么没走到最后 |
|---|---|
| JMeter | 参数化机制很难表达「按实时行情动态触发」,要写复杂预处理器 |
| Locust(Python) | 用代码表达动态参数很自然,但受 GIL 限制,单机并发有瓶颈 |
| **Go + boomer 重写 worker** | 保住动态参数的灵活性,同时突破并发瓶颈 —— 最终选它 |
**一个取舍**:换引擎不难,难的是选对切换时机。第一轮交付沿用原方案保进度,
把调研结论整理成文档同步给团队,后续轮次才切到 Go 方案。
**另一条经验**:本机压测会撞到多层瓶颈(mock 网关、loopback、worker 自身)。
归因时必须说清「这次测出来的瓶颈在哪一层」—— 能定位瓶颈比能跑高 TPS 更值钱。
---
## 目录
```
python/locustfile.py Python worker(4 类订单请求,权重 4:2:2:1)
python/master_locustfile.py Go 压测时的 master 入口(复用统计落盘)
python/stats_dump.py 统计落盘(results/*.json)
go/ boomer worker(编译产物压测,非 go run)
go/third_party/boomer/ vendored boomer v1.6.0 + locust 2.x 协议补丁(MIT)
仅保留编译所需文件,见 THIRD_PARTY.md
target/http_server.py 本机被测 mock(:18099;条件单 endpoint +
可配置单实例上限 TARGET_MAX_QPS / TARGET_EXTRA_LATENCY_MS)
target/mark_price_service.py 标记价格缓存服务(:18097)
target/dispatcher.py 入口分流器(:18100),扩展实验用
scenarios/verify_trigger.py 失真对比实验(写死 vs 缓存驱动,一次跑完两组)
tests/ 21 条单测(去重 / 断流回退 / 触发判定 / 限流 / 分流)
compare.py 报告生成器(数字只来自 results/)
results/ 原始 JSON
report.md 对比报告(由 compare.py 生成)
```
---
## 边界与口径
- 只压本机 mock(`127.0.0.1`),**绝不对外发压**。
- 报告里的数字**必须真实跑出**;`compare.py` 只读 `results/*.json`。
- 两种 worker 必须**同场景、同并发、同请求体**;扩展实验除实例数外参数必须完全一致。
- 接口路径与合约 ID 均为中性自造值,无凭据、无真实域名。
- **口径分栏**:本仓库跑出的数字一律属「**本机演示实测**」;「背景」一节提到的历史业绩属
「**生产真实业绩**」,只作动机,本仓库不提供其证据。两者**不可混写**,也不可互相换算。
---
## 第三方
`go/third_party/boomer` 是 [boomer](https://github.com/myzhan/boomer) v1.6.0 的 vendored 副本
(MIT License, Copyright (c) 2019 myzhan),其上打了 3 处 locust 2.x 协议补丁。
许可证与补丁明细见 [THIRD_PARTY.md](THIRD_PARTY.md)。
副本**只保留了编译与运行所需的 15 个文件**(13 个 `.go` + `go.mod` + `LICENSE`);
上游自带的 `examples/`、`docs/`、自测与 CI 配置已移出(本项目从不引用)。
保留文件的内容未做任何改动(3 处协议补丁除外)。
本仓库自身的 LICENSE 尚未选定 —— 若要公开,需要先补一个。
+68
View File
@@ -0,0 +1,68 @@
# 第三方组件与补丁 / Third-party Components & Patches
## boomer v1.6.0
| 项 | 值 |
|---|---|
| 名称 | boomer(Locust 的 Go 兼容实现,用 Go 写 Locust worker) |
| 版本 | v1.6.0 |
| 上游 | https://github.com/myzhan/boomer |
| 许可证 | **MIT License, Copyright (c) 2019 myzhan** |
| 本地位置 | `go/third_party/boomer/` |
| 引入方式 | vendored 源码副本;`go/go.mod` 里用 `replace github.com/myzhan/boomer => ./third_party/boomer` 指过来 |
`LICENSE` 原样保留在 `go/third_party/boomer/LICENSE`,未做任何修改。
## 为什么 vendored
上游 boomer v1.6.0 只兼容 **locust 1.x** 的 master/slave 通信协议,而本项目的
Locust master 是 **2.x**。不改协议就没法握手,因此把源码放进仓库直接打补丁。
## 关于裁剪(2026-09-22)
上游仓库是整仓复制过来的,其中大部分文件与「编译出一个 Go worker」无关。
本项目**只保留编译与运行所需的文件**(15 个:13 个 `.go` + `go.mod` + `LICENSE`),
移出了上游自带的 `examples/`、`docs/`、`_test.go`、`README*.md`、CI 配置等约 50 个文件。
- 移出的都是**上游自带的示例、文档与自测**,本项目从不引用、也从不运行它们
(`third_party/boomer` 是独立 module,`go test ./...` 不会进入)。
- **没有改动任何被保留文件的内容**(3 处协议补丁除外,见下节)。
- 判据:裁剪前后 `go build` 产出的二进制 **md5 完全一致**,`go mod verify` 通过。
- 若要对照上游原文,去 https://github.com/myzhan/boomer 取 v1.6.0 全量源码即可。
## 打了哪 3 处补丁
全部集中在 `runner.go`(另 `message.go` 有配套小改),补丁位置按行号列出,便于日后
升级 boomer 时对照重打。
| # | 位置 | 改了什么 | 为什么 |
|---|---|---|---|
| 1 | `runner.go:463`、`runner.go:516` | `newMessage("client_ready", nil, ...)` → `newMessage("client_ready", -1, ...)` | locust 2.x 约定用 `-1` 表示「跳过版本检查」;传 `nil` 会被拒绝 |
| 2 | `runner.go:337-342`、`runner.go:259/314/526` | `spawn` 消息从旧的 `num_users` / `spawn_rate` 迁移到 `user_classes_count` / `parsed_options` | locust 2.x 改了 spawn 消息结构,旧字段被忽略 |
| 3 | `runner.go:259/314/526`、`runner.go:315` | `stats` 与 `spawning_complete` 上报 `user_classes_count`(`{"BoomerWorker": numClients}`) | 不上报会被 master 当成 unknown worker 踢掉,表现为「连上了但不发压」 |
> 三处都不改动 boomer 的业务逻辑,只补协议字段 —— 属于「让它能接上 2.x master」的最小改动。
## 如何验证补丁在位
```bash
cd go/third_party/boomer
# 补丁 1
grep -n 'client_ready' runner.go # 期望看到 -1,而不是 nil
# 补丁 2 + 3
grep -n 'user_classes_count' runner.go # 期望 5 处命中:
# 259 / 314 / 526 = 赋值上报
# 337 = 说明注释,342 = 读取 spawn 消息里的值
# 补丁 3
grep -n 'spawning_complete' runner.go
```
端到端验证(起 master 与 go worker,看 worker 是否被认领并出数):
```bash
bash run.sh target
bash run.sh go --users 50 --duration 60s # 若协议不通,master 会一直等 worker
```
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""perf-harness-demo 对比报告生成器。
用法:python3 compare.py results/*.json → 输出 markdown 到 stdout
(run.sh / 验收命令里重定向为 report.md)
报告内容:负载参数核对(公平性)→ worker 指标对比 → 归因分析
→ 失真对比实验(触发率)→ 横向扩展实验(TPS vs 实例数)。
所有数字来自 results/ 下真实跑出来的 JSON,不编造。
"""
import json
import re
import sys
def load(paths):
runs = []
for p in sorted(paths):
with open(p) as f:
d = json.load(f)
d["_file"] = p
runs.append(d)
return runs
def fmt_pct(num, den):
return f"{100.0 * num / den:.2f}%" if den else "0.00%"
def _section_trigger(out, trigger_runs):
"""§5 失真对比实验:写死触发价 vs 缓存服务驱动 的触发率对照。"""
latest = {}
for r in trigger_runs:
latest[r["trigger"]["mode"]] = r # 文件按时间排序,后者覆盖前者 = 最近一轮
out.append("## 5. 失真对比实验(条件单触发率)\n")
out.append("两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`),"
"负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动"
"(contract 1 ≈ 31000 ± 1%)。\n")
out.append("| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 |")
out.append("|---|---|---|---|---|---|---|")
for mode in ("stale", "live"):
r = latest.get(mode)
if not r:
continue
for ph in r["trigger"]["phases"]:
out.append(f"| {r['worker']} | {ph['name']} | {ph['detail']} | "
f"{ph['requests']} | {ph['failures']} | {ph['triggered']} | "
f"{ph['trigger_rate']:.2%} |")
out.append("")
stale, live = latest.get("stale"), latest.get("live")
out.append("**判读**:")
out.append("- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟),"
"**每一轮都「一切正常」**。")
if stale:
rates = " 与 ".join(f"{ph['trigger_rate']:.0%}"
for ph in stale["trigger"]["phases"])
out.append(f"- 但写死触发价的相位触发率塌缩到 **{rates}**:市场状态稍偏离"
"写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义,"
"而报表上看不出任何问题(「数据是错的,但看起来是对的」)。")
if live:
rate = live["trigger"]["phases"][0]["trigger_rate"]
out.append(f"- 缓存服务实时驱动的触发率为 **{rate:.2%}**,落在由行情波动决定的"
"中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。")
out.append("- 缓存服务的滑动窗口去重 / 断流回退语义由 "
"`tests/test_mark_price_service.py` 钉死;触发判定方向由 "
"`tests/test_condition_trigger.py` 钉死。")
out.append("")
def _section_scale(out, scale_runs):
"""§6 横向扩展实验:TPS 随实例数变化(除实例数外参数完全一致)。"""
latest = {}
for r in scale_runs:
m = re.match(r"scale-(\d+)$", r["worker"])
if m:
latest[int(m.group(1))] = r
if not latest:
return
out.append("## 6. 横向扩展实验(单实例上限 → 多实例)\n")
out.append("被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、"
"延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**"
"(worker / 并发 / 时长 / 单实例上限,见「参数」列)。\n")
out.append("| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 |")
out.append("|---|---|---|---|---|---|---|---|")
for n in sorted(latest):
r = latest[n]
t = r["total"]
out.append(f"| {n} | {t['num_requests']} | "
f"{fmt_pct(t['num_failures'], t['num_requests'])} | "
f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} | "
f"{r.get('label', '')} |")
out.append("")
if 1 in latest and len(latest) > 1:
base = latest[1]["total"]["rps"]
top_n = max(latest)
top = latest[top_n]["total"]["rps"]
if base > 0:
out.append(f"**{top_n} 实例 TPS / 1 实例 TPS = {top / base:.2f}**"
f"({top:.0f} vs {base:.0f};不要求线性 —— 分流器与 loopback "
"也会吃一份,TPS 随实例数上升即说明扩展是有效的)。")
out.append("- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**,"
"不是一句「慢」;扩展实例数的决策依据正是这个数字。")
out.append("")
def main(paths):
runs = load(paths)
# 三类结果分开渲染:worker 对比(python/go)、失真实验、扩展实验
bench, trigger_runs, scale_runs = [], [], []
for r in runs:
if "trigger" in r:
trigger_runs.append(r)
elif r["worker"].startswith("scale-"):
scale_runs.append(r)
else:
bench.append(r)
by_worker = {}
for r in bench:
by_worker.setdefault(r["worker"], []).append(r)
out = []
out.append("# perf-harness-demo 对比报告\n")
out.append(f"> 生成自 {len(runs)} 份真实压测结果:"
+ ", ".join(f"`{r['_file']}`" for r in runs) + "\n")
# ★ 数字口径:生产业绩与本机实测必须物理分栏,禁止混写(见 README §数字口径)
out.append("## 0. 数字口径(先读这一节)\n")
out.append("| 口径 | 环境 | 数字 |")
out.append("|---|---|---|")
out.append("| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** "
"| 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS |")
out.append("| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 |")
out.append("")
out.append("> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台,"
"单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。\n")
# 负载参数(公平性核对)
out.append("## 1. 负载参数(公平性核对)\n")
out.append("| worker | users | run_time | host |")
out.append("|---|---|---|---|")
for r in bench:
l = r["load"]
out.append(f"| {r['worker']} | {l['users']} | {l['run_time']} | {l['host']} |")
out.append("\n两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求,"
"权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。\n")
# 指标对比
out.append("## 2. 指标对比(每 worker 取最近一轮)\n")
out.append("| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) |")
out.append("|---|---|---|---|---|---|---|")
latest = {}
for w, rs in by_worker.items():
latest[w] = rs[-1]
for w, r in latest.items():
t = r["total"]
out.append(f"| {w} | {t['num_requests']} | "
f"{fmt_pct(t['num_failures'], t['num_requests'])} | "
f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} |")
ratio = None
if "python" in latest and "go" in latest:
p, g = latest["python"]["total"], latest["go"]["total"]
if p["rps"] > 0:
ratio = g["rps"] / p["rps"]
out.append(f"\n**Go worker TPS 是 Python worker 的 {ratio:.2f} 倍**"
f"({g['rps']:.0f} vs {p['rps']:.0f},同并发同场景)。")
# 分 endpoint 明细
out.append("\n## 3. 分 endpoint 明细\n")
for w, r in latest.items():
out.append(f"### {w}\n")
out.append("| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) |")
out.append("|---|---|---|---|---|---|")
for e in sorted(r["entries"], key=lambda x: x["name"]):
out.append(f"| {e['method']} {e['name']} | {e['num_requests']} | "
f"{e['num_failures']} | {e['rps']:.1f} | {e['p95']} | {e['p99']} |")
out.append("")
# 归因分析
out.append("## 4. 归因分析\n")
out.append("- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL,"
"requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是"
"纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。")
out.append("- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数),"
"网络 I/O 走 netpoller,无全局锁;连接池调优后"
"(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效),"
"单机轻松压出数倍 TPS。")
out.append("- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、"
"loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;"
"若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。"
"本报告数字即按此判读。")
if ratio is not None:
verdict = ("瓶颈在 **Python worker 侧(GIL)**" if ratio > 1.3
else "本轮瓶颈大概率在**被测 mock 服务侧**(两种 worker 都压不满它)"
if ratio <= 1.3 else "不确定")
out.append(f"- **本轮判读**:TPS 比 {ratio:.2f} → {verdict}。")
out.append("")
# 实验分节(失真实验 / 扩展实验),数据缺省时自动跳过
if trigger_runs:
_section_trigger(out, trigger_runs)
if scale_runs:
_section_scale(out, scale_runs)
print("\n".join(out))
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit("usage: compare.py results/*.json")
main(sys.argv[1:])
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+96
View File
@@ -0,0 +1,96 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
)
// newTunedTransport 返回调优后的 Transport。
// 注意:调优参数必须落在**真正被 client 引用**的那个 Transport 上 —— 若参数
// 写在一个从未被使用的变量上,默认 MaxIdleConnsPerHost=2 会让压测根本压不上去,
// 而且**不报任何错**,最难查。因此本文件配套 TestTransportPool,
// 断言「client 实际使用的 transport 就是调优过的那个」。
func newTunedTransport() *http.Transport {
return &http.Transport{
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 2000,
MaxIdleConnsPerHost: 1000,
MaxConnsPerHost: 1000,
IdleConnTimeout: 60 * time.Second,
}
}
// APIClient 是被测 mock 网关的 HTTP 客户端。
type APIClient struct {
base string
hc *http.Client
}
func NewAPIClient(base string) *APIClient {
return &APIClient{
base: base,
hc: &http.Client{
Transport: newTunedTransport(), // ← 调优对象就在这里被引用
Timeout: 10 * time.Second,
},
}
}
// Transport 暴露 client 实际使用的 transport(供断言测试用)。
func (c *APIClient) Transport() *http.Transport {
return c.hc.Transport.(*http.Transport)
}
type apiResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
// do 发起请求并返回 (httpStatus, bizCode, err)。latency 由调用方统计。
func (c *APIClient) do(method, path string, body any) (int, int, error) {
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return 0, -1, err
}
reader = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, c.base+path, reader)
if err != nil {
return 0, -1, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.hc.Do(req)
if err != nil {
return 0, -1, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, -1, err
}
var ar apiResponse
if err := json.Unmarshal(raw, &ar); err != nil {
return resp.StatusCode, -1, fmt.Errorf("decode: %w", err)
}
return resp.StatusCode, ar.Code, nil
}
func (c *APIClient) OpenOrder(path string, p OrderPayload) (int, int, error) {
return c.do(http.MethodPost, path, p)
}
func (c *APIClient) BatchCancel(userID int, orderIDs []int64) (int, int, error) {
return c.do(http.MethodDelete, "/api/v1/order/batch/cancel",
map[string]any{"user_id": userID, "order_ids": orderIDs})
}
+23
View File
@@ -0,0 +1,23 @@
package main
import "testing"
// TestTransportPool:连接池调优参数必须落在 client 实际使用的 transport 上,
// 而不是一个从未被引用的变量(否则调优静默失效)。
func TestTransportPool(t *testing.T) {
c := NewAPIClient("http://127.0.0.1:1")
tr := c.Transport()
if tr == nil {
t.Fatal("client.Transport 为 nil:连接池配置根本没有被引用")
}
if tr.MaxIdleConnsPerHost < 1000 {
t.Fatalf("MaxIdleConnsPerHost = %d,期望 >= 1000(调优未生效)",
tr.MaxIdleConnsPerHost)
}
if tr.MaxConnsPerHost < 1000 {
t.Fatalf("MaxConnsPerHost = %d,期望 >= 1000", tr.MaxConnsPerHost)
}
if tr.MaxIdleConns < 1000 {
t.Fatalf("MaxIdleConns = %d,期望 >= 1000", tr.MaxIdleConns)
}
}
+26
View File
@@ -0,0 +1,26 @@
module perf-harness-demo/go
go 1.25.0
require github.com/myzhan/boomer v1.6.0
require (
github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef // indirect
github.com/clipperhouse/uax29/v2 v2.6.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/shirou/gopsutil v3.21.11+incompatible // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/ugorji/go/codec v1.3.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zeromq/goczmq v4.1.0+incompatible // indirect
github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e // indirect
github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e // indirect
golang.org/x/sys v0.44.0 // indirect
)
replace github.com/myzhan/boomer => ./third_party/boomer
+38
View File
@@ -0,0 +1,38 @@
github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef h1:2JGTg6JapxP9/R33ZaagQtAM4EkkSYnIAlOG5EI8gkM=
github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef/go.mod h1:JS7hed4L1fj0hXcyEejnW57/7LCetXggd+vwrRnYeII=
github.com/clipperhouse/uax29/v2 v2.6.0 h1:z0cDbUV+aPASdFb2/ndFnS9ts/WNXgTNNGFoKXuhpos=
github.com/clipperhouse/uax29/v2 v2.6.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc=
github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/zeromq/goczmq v4.1.0+incompatible h1:cGVQaU6kIwwrGso0Pgbl84tzAz/h7FJ3wYQjSonjFFc=
github.com/zeromq/goczmq v4.1.0+incompatible/go.mod h1:1uZybAJoSRCvZMH2rZxEwWBSmC4T7CB/xQOfChwPEzg=
github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e h1:vGjfCnWv/zWeO1ivv4+OUPgTzG/WV1iGfZwVdtUpLkM=
github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:SkCxcSQ7BQEA9FvDzbj+3hV6EMhSywyxWnHwUXVIyLY=
github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e h1:pjp04/sSr2TYuaPdt+u6Cc1M38Aocp+3er0akr3auFg=
github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:LBjWEodY/ESvKRwLw3bc7mhn49oiI8qlXUqeqLn0pcU=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"flag"
"log"
"github.com/myzhan/boomer"
)
func main() {
// 注意:boomer 在 init 里已注册 --master-host/--master-port 等 flag,
// 这里只新增自己的 flag,绝不能重复定义(会 panic)。
target := flag.String("target", "http://127.0.0.1:18099", "被测 mock 地址(只打本机)")
flag.Parse()
client := NewAPIClient(*target)
tasks := buildBoomerTasks(client)
log.Printf("[go-worker] target=%s, tasks=%d", *target, len(tasks))
boomer.Events.Subscribe("boomer:spawn", func(workers int, spawnRate float64) {
log.Printf("[go-worker] master asks to spawn %d workers (rate %.0f)", workers, spawnRate)
})
boomer.Run(tasks...)
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"sync/atomic"
"time"
"github.com/myzhan/boomer"
)
// OrderPayload 与 python/locustfile.py 的请求体**完全一致**(公平对比前提)。
type OrderPayload struct {
UserID int `json:"user_id"`
ContractID int `json:"contract_id"`
Side string `json:"side"`
MarginType int `json:"margin_type"`
Quantity string `json:"quantity"`
Price string `json:"price,omitempty"`
}
const userPoolSize = 1000
var (
rngMu atomic.Int64 // 简单计数即可,payload 随机性不影响正确性
openOrder atomic.Int64 // 记录一个最近开仓的 order_id 供撤单用
)
func randIntn(n int) int {
// 压测下用原子计数打散即可,不追求密码学随机
return int(rngMu.Add(1) * 2654435761 % (int64(n) * 9973) % int64(n))
}
func payload(withPrice bool) OrderPayload {
p := OrderPayload{
UserID: randIntn(userPoolSize) + 1, // 真随机用户池:避免全员压同一用户导致分布失真
ContractID: randIntn(3) + 1,
MarginType: randIntn(2) + 1,
Quantity: "10",
}
if randIntn(2) == 0 {
p.Side = "ask"
} else {
p.Side = "bid"
}
if withPrice {
p.Price = "30000.5"
}
return p
}
// TaskDef 配置驱动的任务注册。若把任务硬写死在 boomer.Run(t1, t2) 里,
// 新增任务极易漏注册,且不会有任何报错提示。增删任务只改这张表。
type TaskDef struct {
Name string
Weight int
Fn func(c *APIClient) (method, name string, httpStatus, bizCode int, err error)
}
func taskTable() []TaskDef {
return []TaskDef{
{"limit_open", 4, func(c *APIClient) (string, string, int, int, error) {
s, b, err := c.OpenOrder("/api/v1/order/limit/open", payload(true))
return "POST", "/api/v1/order/limit/open", s, b, err
}},
{"market_quantity_open", 2, func(c *APIClient) (string, string, int, int, error) {
s, b, err := c.OpenOrder("/api/v1/order/market/quantity/open", payload(false))
return "POST", "/api/v1/order/market/quantity/open", s, b, err
}},
{"market_amount_open", 2, func(c *APIClient) (string, string, int, int, error) {
s, b, err := c.OpenOrder("/api/v1/order/market/amount/open", payload(false))
return "POST", "/api/v1/order/market/amount/open", s, b, err
}},
{"batch_cancel", 1, func(c *APIClient) (string, string, int, int, error) {
s, b, err := c.BatchCancel(randIntn(userPoolSize)+1,
[]int64{openOrder.Load()})
return "DELETE", "/api/v1/order/batch/cancel", s, b, err
}},
}
}
// buildBoomerTasks 把任务表转成 boomer.Task 列表。
func buildBoomerTasks(c *APIClient) []*boomer.Task {
var tasks []*boomer.Task
for _, d := range taskTable() {
def := d
tasks = append(tasks, &boomer.Task{
Name: def.Name,
Weight: def.Weight,
Fn: func() {
start := time.Now()
method, name, httpStatus, bizCode, err := def.Fn(c)
elapsed := time.Since(start).Milliseconds()
switch {
case err != nil:
boomer.RecordFailure(method, name, elapsed, err.Error())
case httpStatus != 200 || bizCode != 0:
boomer.RecordFailure(method, name, elapsed, "biz error")
default:
boomer.RecordSuccess(method, name, elapsed, 0)
}
},
})
}
return tasks
}
Vendored Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 myzhan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+280
View File
@@ -0,0 +1,280 @@
package boomer
import (
"flag"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/asaskevich/EventBus"
)
// Events is the global event bus instance.
var Events = EventBus.New()
var defaultBoomer = &Boomer{}
// Mode is the running mode of boomer, both standalone and distributed are supported.
type Mode int
const (
// DistributedMode requires connecting to a master.
DistributedMode Mode = iota
// StandaloneMode will run without a master.
StandaloneMode
)
// A Boomer is used to run tasks.
// This type is exposed, so users can create and control a Boomer instance programmatically.
type Boomer struct {
masterHost string
masterPort int
mode Mode
rateLimiter RateLimiter
slaveRunner *slaveRunner
localRunner *localRunner
spawnCount int
spawnRate float64
cpuProfile string
cpuProfileDuration time.Duration
memoryProfile string
memoryProfileDuration time.Duration
outputs []Output
}
// NewBoomer returns a new Boomer.
func NewBoomer(masterHost string, masterPort int) *Boomer {
return &Boomer{
masterHost: masterHost,
masterPort: masterPort,
mode: DistributedMode,
}
}
// NewStandaloneBoomer returns a new Boomer, which can run without master.
func NewStandaloneBoomer(spawnCount int, spawnRate float64) *Boomer {
return &Boomer{
spawnCount: spawnCount,
spawnRate: spawnRate,
mode: StandaloneMode,
}
}
// SetRateLimiter allows user to use their own rate limiter.
// It must be called before the test is started.
func (b *Boomer) SetRateLimiter(rateLimiter RateLimiter) {
b.rateLimiter = rateLimiter
}
// SetMode only accepts boomer.DistributedMode and boomer.StandaloneMode.
func (b *Boomer) SetMode(mode Mode) {
switch mode {
case DistributedMode:
b.mode = DistributedMode
case StandaloneMode:
b.mode = StandaloneMode
default:
log.Println("Invalid mode, ignored!")
}
}
// AddOutput accepts outputs which implements the boomer.Output interface.
func (b *Boomer) AddOutput(o Output) {
b.outputs = append(b.outputs, o)
}
// EnableCPUProfile will start cpu profiling after run.
func (b *Boomer) EnableCPUProfile(cpuProfile string, duration time.Duration) {
b.cpuProfile = cpuProfile
b.cpuProfileDuration = duration
}
// EnableMemoryProfile will start memory profiling after run.
func (b *Boomer) EnableMemoryProfile(memoryProfile string, duration time.Duration) {
b.memoryProfile = memoryProfile
b.memoryProfileDuration = duration
}
// Run accepts a slice of Task and connects to the locust master.
func (b *Boomer) Run(tasks ...*Task) {
if b.cpuProfile != "" {
err := StartCPUProfile(b.cpuProfile, b.cpuProfileDuration)
if err != nil {
log.Printf("Error starting cpu profiling, %v", err)
}
}
if b.memoryProfile != "" {
err := StartMemoryProfile(b.memoryProfile, b.memoryProfileDuration)
if err != nil {
log.Printf("Error starting memory profiling, %v", err)
}
}
switch b.mode {
case DistributedMode:
b.slaveRunner = newSlaveRunner(b.masterHost, b.masterPort, tasks, b.rateLimiter)
for _, o := range b.outputs {
b.slaveRunner.addOutput(o)
}
b.slaveRunner.run()
case StandaloneMode:
b.localRunner = newLocalRunner(tasks, b.rateLimiter, b.spawnCount, b.spawnRate)
for _, o := range b.outputs {
b.localRunner.addOutput(o)
}
b.localRunner.run()
default:
log.Println("Invalid mode, expected boomer.DistributedMode or boomer.StandaloneMode")
}
}
// RecordSuccess reports a success.
func (b *Boomer) RecordSuccess(requestType, name string, responseTime int64, responseLength int64) {
if b.localRunner == nil && b.slaveRunner == nil {
return
}
switch b.mode {
case DistributedMode:
b.slaveRunner.stats.requestSuccessChan <- &requestSuccess{
requestType: requestType,
name: name,
responseTime: responseTime,
responseLength: responseLength,
}
case StandaloneMode:
b.localRunner.stats.requestSuccessChan <- &requestSuccess{
requestType: requestType,
name: name,
responseTime: responseTime,
responseLength: responseLength,
}
}
}
// RecordFailure reports a failure.
func (b *Boomer) RecordFailure(requestType, name string, responseTime int64, exception string) {
if b.localRunner == nil && b.slaveRunner == nil {
return
}
switch b.mode {
case DistributedMode:
b.slaveRunner.stats.requestFailureChan <- &requestFailure{
requestType: requestType,
name: name,
responseTime: responseTime,
error: exception,
}
case StandaloneMode:
b.localRunner.stats.requestFailureChan <- &requestFailure{
requestType: requestType,
name: name,
responseTime: responseTime,
error: exception,
}
}
}
// Quit will send a quit message to the master.
func (b *Boomer) Quit() {
Events.Publish("boomer:quit")
var ticker = time.NewTicker(3 * time.Second)
switch b.mode {
case DistributedMode:
// wait for quit message is sent to master
select {
case <-b.slaveRunner.client.disconnectedChannel():
break
case <-ticker.C:
log.Println("Timeout waiting for sending quit message to master, boomer will quit any way.")
break
}
b.slaveRunner.close()
case StandaloneMode:
b.localRunner.close()
}
}
// Run tasks without connecting to the master.
func runTasksForTest(tasks ...*Task) {
taskNames := strings.Split(runTasks, ",")
for _, task := range tasks {
if task.Name == "" {
continue
} else {
for _, name := range taskNames {
if name == task.Name {
log.Println("Running " + task.Name)
task.Fn()
}
}
}
}
}
// Run accepts a slice of Task and connects to a locust master.
// It's a convenience function to use the defaultBoomer.
func Run(tasks ...*Task) {
if !flag.Parsed() {
flag.Parse()
}
if runTasks != "" {
runTasksForTest(tasks...)
return
}
initLegacyEventHandlers()
rateLimiter, err := createRateLimiter(maxRPS, requestIncreaseRate)
if err != nil {
log.Fatalf("%v\n", err)
}
defaultBoomer.SetRateLimiter(rateLimiter)
defaultBoomer.masterHost = masterHost
defaultBoomer.masterPort = masterPort
defaultBoomer.EnableMemoryProfile(memoryProfile, memoryProfileDuration)
defaultBoomer.EnableCPUProfile(cpuProfile, cpuProfileDuration)
defaultBoomer.Run(tasks...)
quitByMe := false
quitChan := make(chan bool)
Events.SubscribeOnce("boomer:quit", func() {
if !quitByMe {
close(quitChan)
}
})
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
select {
case <-c:
quitByMe = true
defaultBoomer.Quit()
case <-quitChan:
}
log.Println("shut down")
}
// RecordSuccess reports a success.
// It's a convenience function to use the defaultBoomer.
func RecordSuccess(requestType, name string, responseTime int64, responseLength int64) {
defaultBoomer.RecordSuccess(requestType, name, responseTime, responseLength)
}
// RecordFailure reports a failure.
// It's a convenience function to use the defaultBoomer.
func RecordFailure(requestType, name string, responseTime int64, exception string) {
defaultBoomer.RecordFailure(requestType, name, responseTime, exception)
}
+9
View File
@@ -0,0 +1,9 @@
package boomer
type client interface {
connect() (err error)
close()
recvChannel() chan *message
sendChannel() chan *message
disconnectedChannel() chan bool
}
+127
View File
@@ -0,0 +1,127 @@
// +build goczmq
package boomer
import (
"fmt"
"log"
"github.com/zeromq/goczmq"
)
type czmqSocketClient struct {
masterHost string
masterPort int
identity string
dealerSocket *goczmq.Sock
fromMaster chan *message
toMaster chan *message
disconnectedFromMaster chan bool
shutdownChan chan bool
}
func newClient(masterHost string, masterPort int, identity string) (client *czmqSocketClient) {
log.Println("Boomer is built with goczmq support.")
client = &czmqSocketClient{
masterHost: masterHost,
masterPort: masterPort,
identity: identity,
fromMaster: make(chan *message, 100),
toMaster: make(chan *message, 100),
disconnectedFromMaster: make(chan bool),
shutdownChan: make(chan bool),
}
return client
}
func (c *czmqSocketClient) connect() (err error) {
addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort)
dealer := goczmq.NewSock(goczmq.Dealer)
dealer.SetOption(goczmq.SockSetIdentity(c.identity))
err = dealer.Connect(addr)
if err != nil {
return err
}
c.dealerSocket = dealer
log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr)
go c.recv()
go c.send()
return nil
}
func (c *czmqSocketClient) close() {
close(c.shutdownChan)
if c.dealerSocket != nil {
c.dealerSocket.Destroy()
}
}
func (c *czmqSocketClient) recvChannel() chan *message {
return c.fromMaster
}
func (c *czmqSocketClient) recv() {
for {
select {
case <-c.shutdownChan:
return
default:
msg, _, err := c.dealerSocket.RecvFrame()
if err != nil {
log.Printf("Error reading: %v\n", err)
continue
}
decodedMsg, err := newMessageFromBytes(msg)
if err != nil {
log.Printf("Msgpack decode fail: %v\n", err)
continue
}
if decodedMsg.NodeID != c.identity {
log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity)
continue
}
c.fromMaster <- decodedMsg
}
}
}
func (c *czmqSocketClient) sendChannel() chan *message {
return c.toMaster
}
func (c *czmqSocketClient) send() {
for {
select {
case <-c.shutdownChan:
return
case msg := <-c.toMaster:
c.sendMessage(msg)
if msg.Type == "quit" {
c.disconnectedFromMaster <- true
}
}
}
}
func (c *czmqSocketClient) sendMessage(msg *message) {
serializedMessage, err := msg.serialize()
if err != nil {
log.Printf("Msgpack encode fail: %v\n", err)
return
}
err = c.dealerSocket.SendFrame(serializedMessage, goczmq.FlagNone)
if err != nil {
log.Printf("Error sending: %v\n", err)
}
}
func (c *czmqSocketClient) disconnectedChannel() chan bool {
return c.disconnectedFromMaster
}
+129
View File
@@ -0,0 +1,129 @@
// +build !goczmq
package boomer
import (
"fmt"
"log"
"github.com/zeromq/gomq"
"github.com/zeromq/gomq/zmtp"
)
type gomqSocketClient struct {
masterHost string
masterPort int
identity string
dealerSocket gomq.Dealer
fromMaster chan *message
toMaster chan *message
disconnectedFromMaster chan bool
shutdownChan chan bool
}
func newClient(masterHost string, masterPort int, identity string) (client *gomqSocketClient) {
log.Println("Boomer is built with gomq support.")
client = &gomqSocketClient{
masterHost: masterHost,
masterPort: masterPort,
identity: identity,
fromMaster: make(chan *message, 100),
toMaster: make(chan *message, 100),
disconnectedFromMaster: make(chan bool),
shutdownChan: make(chan bool),
}
return client
}
func (c *gomqSocketClient) connect() (err error) {
addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort)
c.dealerSocket = gomq.NewDealer(zmtp.NewSecurityNull(), c.identity)
if err = c.dealerSocket.Connect(addr); err != nil {
return err
}
log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr)
go c.recv()
go c.send()
return nil
}
func (c *gomqSocketClient) close() {
close(c.shutdownChan)
if c.dealerSocket != nil {
c.dealerSocket.Close()
}
}
func (c *gomqSocketClient) recvChannel() chan *message {
return c.fromMaster
}
func (c *gomqSocketClient) recv() {
for {
select {
case <-c.shutdownChan:
return
case msg := <-c.dealerSocket.RecvChannel():
if msg.MessageType == zmtp.CommandMessage {
continue
}
if len(msg.Body) == 0 {
continue
}
body, err := msg.Body[0], msg.Err
if err != nil {
log.Printf("Error reading: %v\n", err)
continue
}
decodedMsg, err := newMessageFromBytes(body)
if err != nil {
log.Printf("Msgpack decode fail: %v\n", err)
continue
}
if decodedMsg.NodeID != c.identity {
log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity)
continue
}
c.fromMaster <- decodedMsg
}
}
}
func (c *gomqSocketClient) sendChannel() chan *message {
return c.toMaster
}
func (c *gomqSocketClient) send() {
for {
select {
case <-c.shutdownChan:
return
case msg := <-c.toMaster:
c.sendMessage(msg)
if msg.Type == "quit" {
c.disconnectedFromMaster <- true
}
}
}
}
func (c *gomqSocketClient) sendMessage(msg *message) {
serializedMessage, err := msg.serialize()
if err != nil {
log.Printf("Msgpack encode fail: %v\n", err)
return
}
err = c.dealerSocket.Send(serializedMessage)
if err != nil {
log.Printf("Error sending: %v\n", err)
}
}
func (c *gomqSocketClient) disconnectedChannel() chan bool {
return c.disconnectedFromMaster
}
+3
View File
@@ -0,0 +1,3 @@
module github.com/myzhan/boomer
go 1.21
+89
View File
@@ -0,0 +1,89 @@
// This file is kept to ensure backward compatibility.
package boomer
import (
"flag"
"fmt"
"log"
"math"
"reflect"
"sync"
"time"
)
var masterHost string
var masterPort int
var maxRPS int64
var requestIncreaseRate string
var runTasks string
var memoryProfile string
var memoryProfileDuration time.Duration
var cpuProfile string
var cpuProfileDuration time.Duration
var successRetiredWarning = &sync.Once{}
var failureRetiredWarning = &sync.Once{}
func createRateLimiter(maxRPS int64, requestIncreaseRate string) (rateLimiter RateLimiter, err error) {
if requestIncreaseRate != "-1" {
if maxRPS > 0 {
log.Println("The max RPS that boomer may generate is limited to", maxRPS, "with a increase rate", requestIncreaseRate)
rateLimiter, err = NewRampUpRateLimiter(maxRPS, requestIncreaseRate, time.Second)
} else {
log.Println("The max RPS that boomer may generate is limited by a increase rate", requestIncreaseRate)
rateLimiter, err = NewRampUpRateLimiter(math.MaxInt64, requestIncreaseRate, time.Second)
}
} else {
if maxRPS > 0 {
log.Println("The max RPS that boomer may generate is limited to", maxRPS)
rateLimiter = NewStableRateLimiter(maxRPS, time.Second)
}
}
return rateLimiter, err
}
// According to locust, responseTime should be int64, in milliseconds.
// But previous version of boomer required responseTime to be float64, so sad.
func convertResponseTime(origin interface{}) int64 {
responseTime := int64(0)
if _, ok := origin.(float64); ok {
responseTime = int64(origin.(float64))
} else if _, ok := origin.(int64); ok {
responseTime = origin.(int64)
} else {
panic(fmt.Sprintf("responseTime should be float64 or int64, not %s", reflect.TypeOf(origin)))
}
return responseTime
}
func legacySuccessHandler(requestType string, name string, responseTime interface{}, responseLength int64) {
successRetiredWarning.Do(func() {
log.Println("boomer.Events.Publish(\"request_success\") is less performant and deprecated, use boomer.RecordSuccess() instead.")
})
defaultBoomer.RecordSuccess(requestType, name, convertResponseTime(responseTime), responseLength)
}
func legacyFailureHandler(requestType string, name string, responseTime interface{}, exception string) {
failureRetiredWarning.Do(func() {
log.Println("boomer.Events.Publish(\"request_failure\") is less performant and deprecated, use boomer.RecordFailure() instead.")
})
defaultBoomer.RecordFailure(requestType, name, convertResponseTime(responseTime), exception)
}
func initLegacyEventHandlers() {
Events.Subscribe("request_success", legacySuccessHandler)
Events.Subscribe("request_failure", legacyFailureHandler)
}
func init() {
flag.Int64Var(&maxRPS, "max-rps", 0, "Max RPS that boomer can generate, disabled by default.")
flag.StringVar(&requestIncreaseRate, "request-increase-rate", "-1", "Request increase rate, disabled by default.")
flag.StringVar(&runTasks, "run-tasks", "", "Run tasks without connecting to the master, multiply tasks is separated by comma. Usually, it's for debug purpose.")
flag.StringVar(&masterHost, "master-host", "127.0.0.1", "Host or IP address of locust master for distributed load testing.")
flag.IntVar(&masterPort, "master-port", 5557, "The port to connect to that is used by the locust master for distributed load testing.")
flag.StringVar(&memoryProfile, "mem-profile", "", "Enable memory profiling.")
flag.DurationVar(&memoryProfileDuration, "mem-profile-duration", 30*time.Second, "Memory profile duration.")
flag.StringVar(&cpuProfile, "cpu-profile", "", "Enable CPU profiling.")
flag.DurationVar(&cpuProfileDuration, "cpu-profile-duration", 30*time.Second, "CPU profile duration.")
}
+38
View File
@@ -0,0 +1,38 @@
package boomer
import (
"github.com/ugorji/go/codec"
)
var (
mh codec.MsgpackHandle
)
type message struct {
Type string `codec:"type"`
Data interface{} `codec:"data"`
NodeID string `codec:"node_id"`
}
func newMessage(t string, data interface{}, nodeID string) (msg *message) {
return &message{
Type: t,
Data: data,
NodeID: nodeID,
}
}
func (m *message) serialize() (out []byte, err error) {
mh.StructToArray = true
enc := codec.NewEncoderBytes(&out, &mh)
err = enc.Encode(m)
return out, err
}
func newMessageFromBytes(raw []byte) (newMsg *message, err error) {
mh.StructToArray = true
dec := codec.NewDecoderBytes(raw, &mh)
newMsg = &message{}
err = dec.Decode(newMsg)
return newMsg, err
}
+146
View File
@@ -0,0 +1,146 @@
package boomer
import (
"fmt"
"os"
"sort"
"strconv"
"time"
"github.com/olekukonko/tablewriter"
)
// Output is primarily responsible for printing test results to different destinations
// such as consoles, files. You can write you own output and add to boomer.
// When running in standalone mode, the default output is ConsoleOutput, you can add more.
// When running in distribute mode, test results will be reported to master with or without
// an output.
// All the OnXXX function will be call in a separated goroutine, just in case some output will block.
// But it will wait for all outputs return to avoid data lost.
type Output interface {
// OnStart will be call before the test starts.
OnStart()
// By default, each output receive stats data from runner every three seconds.
// OnEvent is responsible for dealing with the data.
OnEvent(data map[string]interface{})
// OnStop will be called before the test ends.
OnStop()
}
// ConsoleOutput is the default output for standalone mode.
type ConsoleOutput struct {
}
// NewConsoleOutput returns a ConsoleOutput.
func NewConsoleOutput() *ConsoleOutput {
return &ConsoleOutput{}
}
func getMedianResponseTime(numRequests int64, responseTimes map[int64]int64) int64 {
medianResponseTime := int64(0)
if len(responseTimes) != 0 {
pos := (numRequests - 1) / 2
var sortedKeys []int64
for k := range responseTimes {
sortedKeys = append(sortedKeys, k)
}
sort.Slice(sortedKeys, func(i, j int) bool {
return sortedKeys[i] < sortedKeys[j]
})
for _, k := range sortedKeys {
if pos < responseTimes[k] {
medianResponseTime = k
break
}
pos -= responseTimes[k]
}
}
return medianResponseTime
}
func getAvgResponseTime(numRequests int64, totalResponseTime int64) (avgResponseTime float64) {
avgResponseTime = float64(0)
if numRequests != 0 {
avgResponseTime = float64(totalResponseTime) / float64(numRequests)
}
return avgResponseTime
}
func getAvgContentLength(numRequests int64, totalContentLength int64) (avgContentLength int64) {
avgContentLength = int64(0)
if numRequests != 0 {
avgContentLength = totalContentLength / numRequests
}
return avgContentLength
}
func getCurrentRps(numRequests int64, numReqsPerSecond map[int64]int64) (currentRps int64) {
currentRps = int64(0)
numReqsPerSecondLength := int64(len(numReqsPerSecond))
if numReqsPerSecondLength != 0 {
currentRps = numRequests / numReqsPerSecondLength
}
return currentRps
}
// OnStart of ConsoleOutput has nothing to do.
func (o *ConsoleOutput) OnStart() {
}
// OnStop of ConsoleOutput has nothing to do.
func (o *ConsoleOutput) OnStop() {
}
// OnEvent will print to the console.
func (o *ConsoleOutput) OnEvent(data map[string]interface{}) {
stats, ok := data["stats"].([]interface{})
if !ok {
return
}
currentTime := time.Now()
println(fmt.Sprintf("Current time: %s", currentTime.Format("2006/01/02 15:04:05")))
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Type", "Name", "# requests", "# fails", "Median", "Average", "Min", "Max", "Content Size", "# reqs/sec"})
for _, stat := range stats {
s := stat.(map[string]interface{})
row := make([]string, 10)
row[0], row[1] = s["name"].(string), s["method"].(string)
numRequests := s["num_requests"].(int64)
row[2] = strconv.FormatInt(numRequests, 10)
numFailures := s["num_failures"].(int64)
row[3] = strconv.FormatInt(numFailures, 10)
medianResponseTime := getMedianResponseTime(numRequests, s["response_times"].(map[int64]int64))
row[4] = strconv.FormatInt(medianResponseTime, 10)
totalResponseTime := s["total_response_time"].(int64)
avgResponseTime := getAvgResponseTime(numRequests, totalResponseTime)
row[5] = strconv.FormatFloat(avgResponseTime, 'f', 2, 64)
minResponseTime := s["min_response_time"].(int64)
row[6] = strconv.FormatInt(minResponseTime, 10)
maxResponseTime := s["max_response_time"].(int64)
row[7] = strconv.FormatInt(maxResponseTime, 10)
totalContentLength := s["total_content_length"].(int64)
avgContentLength := getAvgContentLength(numRequests, totalContentLength)
row[8] = strconv.FormatInt(avgContentLength, 10)
numReqsPerSecond := s["num_reqs_per_sec"].(map[int64]int64)
currentRps := getCurrentRps(numRequests, numReqsPerSecond)
row[9] = strconv.FormatInt(currentRps, 10)
table.Append(row)
}
table.Render()
println()
}
+213
View File
@@ -0,0 +1,213 @@
package boomer
import (
"errors"
"math"
"strconv"
"strings"
"sync/atomic"
"time"
)
// RateLimiter is used to put limits on task executions.
type RateLimiter interface {
// Start is used to enable the rate limiter.
// It can be implemented as a noop if not needed.
Start()
// Acquire() is called before executing a task.Fn function.
// If Acquire() returns true, the task.Fn function will be executed.
// If Acquire() returns false, the task.Fn function won't be executed this time, but Acquire() will be called very soon.
// It works like:
// for {
// blocked := rateLimiter.Acquire()
// if !blocked {
// task.Fn()
// }
// }
// Acquire() should block the caller until execution is allowed.
Acquire() bool
// Stop is used to disable the rate limiter.
// It can be implemented as a noop if not needed.
Stop()
}
// A StableRateLimiter uses the token bucket algorithm.
// the bucket is refilled according to the refill period, no burst is allowed.
type StableRateLimiter struct {
threshold int64
currentThreshold int64
refillPeriod time.Duration
broadcastChannel chan bool
quitChannel chan bool
}
// NewStableRateLimiter returns a StableRateLimiter.
func NewStableRateLimiter(threshold int64, refillPeriod time.Duration) (rateLimiter *StableRateLimiter) {
rateLimiter = &StableRateLimiter{
threshold: threshold,
currentThreshold: threshold,
refillPeriod: refillPeriod,
broadcastChannel: make(chan bool),
}
return rateLimiter
}
// Start to refill the bucket periodically.
func (limiter *StableRateLimiter) Start() {
limiter.quitChannel = make(chan bool)
quitChannel := limiter.quitChannel
go func() {
for {
select {
case <-quitChannel:
return
default:
atomic.StoreInt64(&limiter.currentThreshold, limiter.threshold)
time.Sleep(limiter.refillPeriod)
close(limiter.broadcastChannel)
limiter.broadcastChannel = make(chan bool)
}
}
}()
}
// Acquire a token from the bucket, returns true if the bucket is exhausted.
func (limiter *StableRateLimiter) Acquire() (blocked bool) {
permit := atomic.AddInt64(&limiter.currentThreshold, -1)
if permit < 0 {
blocked = true
// block until the bucket is refilled
<-limiter.broadcastChannel
} else {
blocked = false
}
return blocked
}
// Stop the rate limiter.
func (limiter *StableRateLimiter) Stop() {
close(limiter.quitChannel)
}
// ErrParsingRampUpRate is the error returned if the format of rampUpRate is invalid.
var ErrParsingRampUpRate = errors.New("ratelimiter: invalid format of rampUpRate, try \"1\" or \"1/1s\"")
// A RampUpRateLimiter uses the token bucket algorithm.
// the threshold is updated according to the warm up rate.
// the bucket is refilled according to the refill period, no burst is allowed.
type RampUpRateLimiter struct {
maxThreshold int64
nextThreshold int64
currentThreshold int64
refillPeriod time.Duration
rampUpRate string
rampUpStep int64
rampUpPeroid time.Duration
broadcastChannel chan bool
rampUpChannel chan bool
quitChannel chan bool
}
// NewRampUpRateLimiter returns a RampUpRateLimiter.
// Valid formats of rampUpRate are "1", "1/1s".
func NewRampUpRateLimiter(maxThreshold int64, rampUpRate string, refillPeriod time.Duration) (rateLimiter *RampUpRateLimiter, err error) {
rateLimiter = &RampUpRateLimiter{
maxThreshold: maxThreshold,
nextThreshold: 0,
currentThreshold: 0,
rampUpRate: rampUpRate,
refillPeriod: refillPeriod,
broadcastChannel: make(chan bool),
}
rateLimiter.rampUpStep, rateLimiter.rampUpPeroid, err = rateLimiter.parseRampUpRate(rateLimiter.rampUpRate)
if err != nil {
return nil, err
}
return rateLimiter, nil
}
func (limiter *RampUpRateLimiter) parseRampUpRate(rampUpRate string) (rampUpStep int64, rampUpPeroid time.Duration, err error) {
if strings.Contains(rampUpRate, "/") {
tmp := strings.Split(rampUpRate, "/")
if len(tmp) != 2 {
return rampUpStep, rampUpPeroid, ErrParsingRampUpRate
}
rampUpStep, err := strconv.ParseInt(tmp[0], 10, 64)
if err != nil {
return rampUpStep, rampUpPeroid, ErrParsingRampUpRate
}
rampUpPeroid, err := time.ParseDuration(tmp[1])
if err != nil {
return rampUpStep, rampUpPeroid, ErrParsingRampUpRate
}
return rampUpStep, rampUpPeroid, nil
}
rampUpStep, err = strconv.ParseInt(rampUpRate, 10, 64)
if err != nil {
return rampUpStep, rampUpPeroid, ErrParsingRampUpRate
}
rampUpPeroid = time.Second
return rampUpStep, rampUpPeroid, nil
}
// Start to refill the bucket periodically.
func (limiter *RampUpRateLimiter) Start() {
limiter.quitChannel = make(chan bool)
quitChannel := limiter.quitChannel
// bucket updater
go func() {
for {
select {
case <-quitChannel:
return
default:
atomic.StoreInt64(&limiter.currentThreshold, limiter.nextThreshold)
time.Sleep(limiter.refillPeriod)
close(limiter.broadcastChannel)
limiter.broadcastChannel = make(chan bool)
}
}
}()
// threshold updater
go func() {
for {
select {
case <-quitChannel:
return
default:
nextValue := limiter.nextThreshold + limiter.rampUpStep
if nextValue < 0 {
// int64 overflow
nextValue = int64(math.MaxInt64)
}
if nextValue > limiter.maxThreshold {
nextValue = limiter.maxThreshold
}
atomic.StoreInt64(&limiter.nextThreshold, nextValue)
time.Sleep(limiter.rampUpPeroid)
}
}
}()
}
// Acquire a token from the bucket, returns true if the bucket is exhausted.
func (limiter *RampUpRateLimiter) Acquire() (blocked bool) {
permit := atomic.AddInt64(&limiter.currentThreshold, -1)
if permit < 0 {
blocked = true
// block until the bucket is refilled
<-limiter.broadcastChannel
} else {
blocked = false
}
return blocked
}
// Stop the rate limiter.
func (limiter *RampUpRateLimiter) Stop() {
limiter.nextThreshold = 0
close(limiter.quitChannel)
}
+555
View File
@@ -0,0 +1,555 @@
package boomer
import (
"fmt"
"log"
"math/rand"
"os"
"runtime/debug"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
stateInit = "ready"
stateSpawning = "spawning"
stateRunning = "running"
stateStopped = "stopped"
stateQuitting = "quitting"
)
const (
slaveReportInterval = 3 * time.Second
heartbeatInterval = 1 * time.Second
)
type runner struct {
state string
tasks []*Task
totalTaskWeight int
rateLimiter RateLimiter
rateLimitEnabled bool
stats *requestStats
numClients int32
spawnRate float64
// all running workers(goroutines) will select on this channel.
// close this channel will stop all running workers.
stopChan chan bool
// close this channel will stop all goroutines used in runner.
closeChan chan bool
outputs []Output
}
// safeRun runs fn and recovers from unexpected panics.
// it prevents panics from Task.Fn crashing boomer.
func (r *runner) safeRun(fn func()) {
defer func() {
// don't panic
err := recover()
if err != nil {
stackTrace := debug.Stack()
errMsg := fmt.Sprintf("%v", err)
os.Stderr.Write([]byte(errMsg))
os.Stderr.Write([]byte("\n"))
os.Stderr.Write(stackTrace)
}
}()
fn()
}
func (r *runner) addOutput(o Output) {
r.outputs = append(r.outputs, o)
}
func (r *runner) outputOnStart() {
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnStart()
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) outputOnEevent(data map[string]interface{}) {
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnEvent(data)
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) outputOnStop() {
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnStop()
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) spawnWorkers(spawnCount int, quit chan bool, spawnCompleteFunc func()) {
log.Println("Spawning", spawnCount, "clients at the rate", r.spawnRate, "clients/s...")
for i := 1; i <= spawnCount; i++ {
sleepTime := time.Duration(1000000/r.spawnRate) * time.Microsecond
time.Sleep(sleepTime)
select {
case <-quit:
// quit spawning goroutine
return
default:
atomic.AddInt32(&r.numClients, 1)
go func() {
for {
select {
case <-quit:
return
default:
if r.rateLimitEnabled {
blocked := r.rateLimiter.Acquire()
if !blocked {
task := r.getTask()
r.safeRun(task.Fn)
}
} else {
task := r.getTask()
r.safeRun(task.Fn)
}
}
}
}()
}
}
if spawnCompleteFunc != nil {
spawnCompleteFunc()
}
}
// setTasks will set the runner's task list AND the total task weight
// which is used to get a random task later
func (r *runner) setTasks(t []*Task) {
r.tasks = t
weightSum := 0
for _, task := range r.tasks {
weightSum += task.Weight
}
r.totalTaskWeight = weightSum
}
func (r *runner) getTask() *Task {
tasksCount := len(r.tasks)
if tasksCount == 1 {
// Fast path
return r.tasks[0]
}
rs := rand.New(rand.NewSource(time.Now().UnixNano()))
totalWeight := r.totalTaskWeight
if totalWeight <= 0 {
// If all the tasks have not weights defined, they have the same chance to run
randNum := rs.Intn(tasksCount)
return r.tasks[randNum]
}
randNum := rs.Intn(totalWeight)
runningSum := 0
for _, task := range r.tasks {
runningSum += task.Weight
if runningSum > randNum {
return task
}
}
return nil
}
func (r *runner) startSpawning(spawnCount int, spawnRate float64, spawnCompleteFunc func()) {
Events.Publish("boomer:hatch", spawnCount, spawnRate)
Events.Publish("boomer:spawn", spawnCount, spawnRate)
r.stats.clearStatsChan <- true
r.stopChan = make(chan bool)
r.spawnRate = spawnRate
r.numClients = 0
go r.spawnWorkers(spawnCount, r.stopChan, spawnCompleteFunc)
}
func (r *runner) stop() {
// publish the boomer stop event
// user's code can subscribe to this event and do thins like cleaning up
Events.Publish("boomer:stop")
// stop previous goroutines without blocking
// those goroutines will exit when r.safeRun returns
close(r.stopChan)
if r.rateLimitEnabled {
r.rateLimiter.Stop()
}
}
type localRunner struct {
runner
spawnCount int
}
func newLocalRunner(tasks []*Task, rateLimiter RateLimiter, spawnCount int, spawnRate float64) (r *localRunner) {
r = &localRunner{}
r.setTasks(tasks)
r.spawnRate = spawnRate
r.spawnCount = spawnCount
r.closeChan = make(chan bool)
r.addOutput(NewConsoleOutput())
if rateLimiter != nil {
r.rateLimitEnabled = true
r.rateLimiter = rateLimiter
}
r.stats = newRequestStats()
return r
}
func (r *localRunner) run() {
r.state = stateInit
r.stats.start()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for {
select {
case data := <-r.stats.messageToRunnerChan:
data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)}
r.outputOnEevent(data)
case <-r.closeChan:
Events.Publish("boomer:quit")
r.stop()
wg.Done()
return
}
}
}()
if r.rateLimitEnabled {
r.rateLimiter.Start()
}
r.startSpawning(r.spawnCount, r.spawnRate, nil)
wg.Wait()
}
func (r *localRunner) close() {
if r.stats != nil {
r.stats.close()
}
close(r.closeChan)
}
// SlaveRunner connects to the master, spawns goroutines and collects stats.
type slaveRunner struct {
runner
nodeID string
masterHost string
masterPort int
client client
}
func newSlaveRunner(masterHost string, masterPort int, tasks []*Task, rateLimiter RateLimiter) (r *slaveRunner) {
r = &slaveRunner{}
r.masterHost = masterHost
r.masterPort = masterPort
r.setTasks(tasks)
r.nodeID = getNodeID()
r.closeChan = make(chan bool)
if rateLimiter != nil {
r.rateLimitEnabled = true
r.rateLimiter = rateLimiter
}
r.stats = newRequestStats()
return r
}
func (r *slaveRunner) spawnComplete() {
data := make(map[string]interface{})
data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)}
r.client.sendChannel() <- newMessage("spawning_complete", data, r.nodeID)
r.state = stateRunning
}
func (r *slaveRunner) onQuiting() {
if r.state != stateQuitting {
r.client.sendChannel() <- newMessage("quit", nil, r.nodeID)
}
}
func (r *slaveRunner) close() {
if r.stats != nil {
r.stats.close()
}
if r.client != nil {
r.client.close()
}
close(r.closeChan)
}
func (r *slaveRunner) onSpawnMessage(msg *message) {
r.client.sendChannel() <- newMessage("spawning", nil, r.nodeID)
// locust >= 2.0: user_classes_count is a map[class]count; spawn_rate lives
// in parsed_options. Fall back to legacy num_users/spawn_rate fields.
var spawnRate float64
workers := 0
data := msgDataMap(msg)
if ucc, ok := data["user_classes_count"]; ok {
switch m := ucc.(type) {
case map[string]interface{}:
for _, v := range m {
workers += int(toInt64(v))
}
case map[interface{}]interface{}:
for _, v := range m {
workers += int(toInt64(v))
}
}
if po, ok := data["parsed_options"]; ok {
switch pm := po.(type) {
case map[string]interface{}:
if sr, ok := pm["spawn_rate"]; ok {
spawnRate = toFloat64(sr)
}
case map[interface{}]interface{}:
if sr, ok := pm["spawn_rate"]; ok {
spawnRate = toFloat64(sr)
}
}
}
} else {
rate := data["spawn_rate"]
users := data["num_users"]
spawnRate = rate.(float64)
if _, ok := users.(uint64); ok {
workers = int(users.(uint64))
} else {
workers = int(users.(int64))
}
}
if spawnRate <= 0 {
spawnRate = float64(workers)
}
if r.rateLimitEnabled {
r.rateLimiter.Start()
}
r.startSpawning(workers, spawnRate, r.spawnComplete)
}
func msgDataMap(msg *message) map[string]interface{} {
switch m := msg.Data.(type) {
case map[string]interface{}:
return m
case map[interface{}]interface{}:
out := make(map[string]interface{}, len(m))
for k, v := range m {
if ks, ok := k.(string); ok {
out[ks] = v
}
}
return out
}
return nil
}
func toInt64(v interface{}) int64 {
switch n := v.(type) {
case int64:
return n
case uint64:
return int64(n)
case int:
return int64(n)
case int32:
return int64(n)
case uint32:
return int64(n)
case float64:
return int64(n)
}
return 0
}
func toFloat64(v interface{}) float64 {
switch n := v.(type) {
case float64:
return n
case int64:
return float64(n)
case uint64:
return float64(n)
case int:
return float64(n)
}
return 0
}
// Runner acts as a state machine.
func (r *slaveRunner) onMessage(msg *message) {
if msg.Type == "hatch" {
log.Println("The master sent a 'hatch' message, you are using an unsupported locust version, please update locust to 1.2.")
return
}
switch r.state {
case stateInit:
switch msg.Type {
case "spawn":
r.state = stateSpawning
r.onSpawnMessage(msg)
case "quit":
Events.Publish("boomer:quit")
}
case stateSpawning:
fallthrough
case stateRunning:
switch msg.Type {
case "spawn":
r.state = stateSpawning
r.stop()
r.onSpawnMessage(msg)
case "stop":
r.stop()
r.state = stateStopped
log.Println("Recv stop message from master, all the goroutines are stopped")
r.client.sendChannel() <- newMessage("client_stopped", nil, r.nodeID)
r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID)
r.state = stateInit
case "quit":
r.stop()
log.Println("Recv quit message from master, all the goroutines are stopped")
Events.Publish("boomer:quit")
r.state = stateInit
}
case stateStopped:
switch msg.Type {
case "spawn":
r.state = stateSpawning
r.onSpawnMessage(msg)
case "quit":
Events.Publish("boomer:quit")
r.state = stateInit
}
}
}
func (r *slaveRunner) startListener() {
go func() {
for {
select {
case msg := <-r.client.recvChannel():
r.onMessage(msg)
case <-r.closeChan:
return
}
}
}()
}
func (r *slaveRunner) run() {
r.state = stateInit
r.client = newClient(r.masterHost, r.masterPort, r.nodeID)
err := r.client.connect()
if err != nil {
if strings.Contains(err.Error(), "Socket type DEALER is not compatible with PULL") {
log.Println("Newer version of locust changes ZMQ socket to DEALER and ROUTER, you should update your locust version.")
} else {
log.Printf("Failed to connect to master(%s:%d) with error %v\n", r.masterHost, r.masterPort, err)
}
return
}
// listen to master
r.startListener()
r.stats.start()
// tell master, I'm ready
r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID)
// report to master
go func() {
for {
select {
case data := <-r.stats.messageToRunnerChan:
if r.state == stateInit || r.state == stateStopped {
continue
}
data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)}
r.client.sendChannel() <- newMessage("stats", data, r.nodeID)
r.outputOnEevent(data)
case <-r.closeChan:
return
}
}
}()
// heartbeat
// See: https://github.com/locustio/locust/commit/a8c0d7d8c588f3980303358298870f2ea394ab93
go func() {
var ticker = time.NewTicker(heartbeatInterval)
for {
select {
case <-ticker.C:
CPUUsage := GetCurrentCPUUsage()
data := map[string]interface{}{
"state": r.state,
"current_cpu_usage": CPUUsage,
}
r.client.sendChannel() <- newMessage("heartbeat", data, r.nodeID)
case <-r.closeChan:
return
}
}
}()
Events.Subscribe("boomer:quit", r.onQuiting)
}
+309
View File
@@ -0,0 +1,309 @@
package boomer
import (
"time"
)
type requestSuccess struct {
requestType string
name string
responseTime int64
responseLength int64
}
type requestFailure struct {
requestType string
name string
responseTime int64
error string
}
type requestStats struct {
entries map[string]*statsEntry
errors map[string]*statsError
total *statsEntry
startTime int64
requestSuccessChan chan *requestSuccess
requestFailureChan chan *requestFailure
clearStatsChan chan bool
messageToRunnerChan chan map[string]interface{}
shutdownChan chan bool
}
func newRequestStats() (stats *requestStats) {
entries := make(map[string]*statsEntry)
errors := make(map[string]*statsError)
stats = &requestStats{
entries: entries,
errors: errors,
}
stats.requestSuccessChan = make(chan *requestSuccess, 100)
stats.requestFailureChan = make(chan *requestFailure, 100)
stats.clearStatsChan = make(chan bool)
stats.messageToRunnerChan = make(chan map[string]interface{}, 10)
stats.shutdownChan = make(chan bool)
stats.total = &statsEntry{
name: "Total",
method: "",
}
stats.total.reset()
return stats
}
func (s *requestStats) logRequest(method, name string, responseTime int64, contentLength int64) {
s.total.log(responseTime, contentLength)
s.get(name, method).log(responseTime, contentLength)
}
func (s *requestStats) logError(method, name, err string) {
s.total.logError(err)
s.get(name, method).logError(err)
// store error in errors map
key := MD5(method, name, err)
entry, ok := s.errors[key]
if !ok {
entry = &statsError{
name: name,
method: method,
error: err,
}
s.errors[key] = entry
}
entry.occured()
}
func (s *requestStats) get(name string, method string) (entry *statsEntry) {
entry, ok := s.entries[name+method]
if !ok {
newEntry := &statsEntry{
name: name,
method: method,
numReqsPerSec: make(map[int64]int64),
responseTimes: make(map[int64]int64),
}
newEntry.reset()
s.entries[name+method] = newEntry
return newEntry
}
return entry
}
func (s *requestStats) clearAll() {
s.total = &statsEntry{
name: "Total",
method: "",
}
s.total.reset()
s.entries = make(map[string]*statsEntry)
s.errors = make(map[string]*statsError)
s.startTime = time.Now().Unix()
}
func (s *requestStats) serializeStats() []interface{} {
entries := make([]interface{}, 0, len(s.entries))
for _, v := range s.entries {
if !(v.numRequests == 0 && v.numFailures == 0) {
entries = append(entries, v.getStrippedReport())
}
}
return entries
}
func (s *requestStats) serializeErrors() map[string]map[string]interface{} {
errors := make(map[string]map[string]interface{})
for k, v := range s.errors {
errors[k] = v.toMap()
}
return errors
}
func (s *requestStats) collectReportData() map[string]interface{} {
data := make(map[string]interface{})
data["stats"] = s.serializeStats()
data["stats_total"] = s.total.getStrippedReport()
data["errors"] = s.serializeErrors()
s.errors = make(map[string]*statsError)
return data
}
func (s *requestStats) start() {
go func() {
var ticker = time.NewTicker(slaveReportInterval)
for {
select {
case m := <-s.requestSuccessChan:
s.logRequest(m.requestType, m.name, m.responseTime, m.responseLength)
case n := <-s.requestFailureChan:
s.logRequest(n.requestType, n.name, n.responseTime, 0)
s.logError(n.requestType, n.name, n.error)
case <-s.clearStatsChan:
s.clearAll()
case <-ticker.C:
data := s.collectReportData()
// send data to channel, no network IO in this goroutine
s.messageToRunnerChan <- data
case <-s.shutdownChan:
return
}
}
}()
}
// close is used by unit tests to avoid leakage of goroutines
func (s *requestStats) close() {
close(s.shutdownChan)
}
type statsEntry struct {
name string
method string
numRequests int64
numFailures int64
totalResponseTime int64
minResponseTime int64
maxResponseTime int64
numReqsPerSec map[int64]int64
numFailPerSec map[int64]int64
responseTimes map[int64]int64
totalContentLength int64
startTime int64
lastRequestTimestamp int64
}
func (s *statsEntry) reset() {
s.startTime = time.Now().Unix()
s.numRequests = 0
s.numFailures = 0
s.totalResponseTime = 0
s.responseTimes = make(map[int64]int64)
s.minResponseTime = 0
s.maxResponseTime = 0
s.lastRequestTimestamp = time.Now().Unix()
s.numReqsPerSec = make(map[int64]int64)
s.numFailPerSec = make(map[int64]int64)
s.totalContentLength = 0
}
func (s *statsEntry) log(responseTime int64, contentLength int64) {
s.numRequests++
s.logTimeOfRequest()
s.logResponseTime(responseTime)
s.totalContentLength += contentLength
}
func (s *statsEntry) logTimeOfRequest() {
key := time.Now().Unix()
_, ok := s.numReqsPerSec[key]
if !ok {
s.numReqsPerSec[key] = 1
} else {
s.numReqsPerSec[key]++
}
s.lastRequestTimestamp = key
}
func (s *statsEntry) logResponseTime(responseTime int64) {
s.totalResponseTime += responseTime
if s.minResponseTime == 0 {
s.minResponseTime = responseTime
}
if responseTime < s.minResponseTime {
s.minResponseTime = responseTime
}
if responseTime > s.maxResponseTime {
s.maxResponseTime = responseTime
}
var roundedResponseTime int64
// to avoid to much data that has to be transferred to the master node when
// running in distributed mode, we save the response time rounded in a dict
// so that 147 becomes 150, 3432 becomes 3400 and 58760 becomes 59000
// see also locust's stats.py
if responseTime < 100 {
roundedResponseTime = responseTime
} else if responseTime < 1000 {
roundedResponseTime = int64(round(float64(responseTime), .5, -1))
} else if responseTime < 10000 {
roundedResponseTime = int64(round(float64(responseTime), .5, -2))
} else {
roundedResponseTime = int64(round(float64(responseTime), .5, -3))
}
_, ok := s.responseTimes[roundedResponseTime]
if !ok {
s.responseTimes[roundedResponseTime] = 1
} else {
s.responseTimes[roundedResponseTime]++
}
}
func (s *statsEntry) logError(err string) {
s.numFailures++
key := time.Now().Unix()
_, ok := s.numFailPerSec[key]
if !ok {
s.numFailPerSec[key] = 1
} else {
s.numFailPerSec[key]++
}
}
func (s *statsEntry) serialize() map[string]interface{} {
result := make(map[string]interface{})
result["name"] = s.name
result["method"] = s.method
result["last_request_timestamp"] = s.lastRequestTimestamp
result["start_time"] = s.startTime
result["num_requests"] = s.numRequests
// Boomer doesn't allow None response time for requests like locust.
// num_none_requests is added to keep compatible with locust.
result["num_none_requests"] = 0
result["num_failures"] = s.numFailures
result["total_response_time"] = s.totalResponseTime
result["max_response_time"] = s.maxResponseTime
result["min_response_time"] = s.minResponseTime
result["total_content_length"] = s.totalContentLength
result["response_times"] = s.responseTimes
result["num_reqs_per_sec"] = s.numReqsPerSec
result["num_fail_per_sec"] = s.numFailPerSec
return result
}
func (s *statsEntry) getStrippedReport() map[string]interface{} {
report := s.serialize()
s.reset()
return report
}
type statsError struct {
name string
method string
error string
occurrences int64
}
func (err *statsError) occured() {
err.occurrences++
}
func (err *statsError) toMap() map[string]interface{} {
m := make(map[string]interface{})
m["method"] = err.method
m["name"] = err.name
m["error"] = err.error
m["occurrences"] = err.occurrences
return m
}
+13
View File
@@ -0,0 +1,13 @@
package boomer
// Task is like the "Locust object" in locust, the python version.
// When boomer receives a start message from master, it will spawn several goroutines to run Task.Fn.
// But users can keep some information in the python version, they can't do the same things in boomer.
// Because Task.Fn is a pure function.
type Task struct {
// The weight is used to distribute goroutines over multiple tasks.
Weight int
// Fn is called by the goroutines allocated to this task, in a loop.
Fn func()
Name string
}
+107
View File
@@ -0,0 +1,107 @@
package boomer
import (
"math/rand"
"sync"
"time"
)
// TaskSet is an experimental feature, the API is not stabilized.
// It needs to be more considered and tested.
type TaskSet interface {
// Add a Task to the TaskSet.
AddTask(task *Task)
// Set the weight of the TaskSet.
SetWeight(weight int)
// Get the weight of the TaskSet.
GetWeight() (weight int)
// Run will pick up a Task from the TaskSet and run.
Run()
}
// WeighingTaskSet is a implementation of the TaskSet interface.
// When a Task is added to WeighingTaskSet, it's weight is used
// to calculate the probability to be called.
type WeighingTaskSet struct {
weight int
offset int
tasks []*Task
index []int
lock sync.RWMutex
}
// NewWeighingTaskSet returns a new WeighingTaskSet.
func NewWeighingTaskSet() *WeighingTaskSet {
return &WeighingTaskSet{
weight: 0,
offset: 0,
tasks: make([]*Task, 0),
index: make([]int, 0),
}
}
// AddTask add a Task to the Weighing TaskSet.
// If the task's weight is <=0, it will be ignored.
func (ts *WeighingTaskSet) AddTask(task *Task) {
if task.Weight <= 0 {
return
}
ts.lock.Lock()
ts.tasks = append(ts.tasks, task)
ts.offset = ts.offset + task.Weight
ts.index = append(ts.index, ts.offset)
ts.lock.Unlock()
}
func (ts *WeighingTaskSet) binarySearch(roll int) (task *Task) {
left := 0
right := len(ts.index) - 1
for left <= right {
mid := (left + right) / 2
if left == mid {
if roll < ts.index[mid] {
return ts.tasks[mid]
}
return ts.tasks[mid+1]
}
if ts.index[mid-1] <= roll && roll < ts.index[mid] {
return ts.tasks[mid]
}
if roll < ts.index[mid-1] {
right = mid - 1
} else {
left = mid + 1
}
}
return nil
}
// GetTask returns a task in the task set.
func (ts *WeighingTaskSet) GetTask(roll int) (task *Task) {
if roll < 0 || roll >= ts.offset {
return nil
}
ts.lock.RLock()
task = ts.binarySearch(roll)
ts.lock.RUnlock()
return task
}
// SetWeight sets the weight of the task set.
func (ts *WeighingTaskSet) SetWeight(weight int) {
ts.weight = weight
}
// GetWeight returns the weight of the task set.
func (ts *WeighingTaskSet) GetWeight() (weight int) {
return ts.weight
}
// Run will pick up a task in the task set randomly and run.
// It can is used as a Task.Fn.
func (ts *WeighingTaskSet) Run() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
roll := r.Intn(ts.offset)
task := ts.GetTask(roll)
task.Fn()
}
+110
View File
@@ -0,0 +1,110 @@
package boomer
import (
"crypto/md5"
"fmt"
"io"
"log"
"math"
"os"
"runtime"
"runtime/pprof"
"strings"
"time"
"github.com/google/uuid"
"github.com/shirou/gopsutil/process"
)
func round(val float64, roundOn float64, places int) (newVal float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
newVal = round / pow
return
}
// MD5 returns the md5 hash of strings.
func MD5(slice ...string) string {
h := md5.New()
for _, v := range slice {
io.WriteString(h, v)
}
return fmt.Sprintf("%x", h.Sum(nil))
}
// generate a random nodeID like locust does, using the same algorithm.
func getNodeID() (nodeID string) {
hostname, _ := os.Hostname()
id := strings.Replace(uuid.New().String(), "-", "", -1)
nodeID = fmt.Sprintf("%s_%s", hostname, id)
return
}
// Now returns the current timestamp in milliseconds.
func Now() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
// StartMemoryProfile starts memory profiling and save the results in file.
func StartMemoryProfile(file string, duration time.Duration) (err error) {
f, err := os.Create(file)
if err != nil {
return err
}
log.Println("Start memory profiling for", duration)
time.AfterFunc(duration, func() {
err = pprof.WriteHeapProfile(f)
if err != nil {
log.Println(err)
}
f.Close()
log.Println("Stop memory profiling after", duration)
})
return nil
}
// StartCPUProfile starts cpu profiling and save the results in file.
func StartCPUProfile(file string, duration time.Duration) (err error) {
f, err := os.Create(file)
if err != nil {
return err
}
log.Println("Start cpu profiling for", duration)
err = pprof.StartCPUProfile(f)
if err != nil {
f.Close()
return err
}
time.AfterFunc(duration, func() {
pprof.StopCPUProfile()
f.Close()
log.Println("Stop CPU profiling after", duration)
})
return nil
}
// GetCurrentCPUUsage get current CPU usage
func GetCurrentCPUUsage() float64 {
currentPid := os.Getpid()
p, err := process.NewProcess(int32(currentPid))
if err != nil {
log.Printf("Fail to get CPU percent, %v\n", err)
return 0.0
}
percent, err := p.CPUPercent()
if err != nil {
log.Printf("Fail to get CPU percent, %v\n", err)
return 0.0
}
return percent / float64(runtime.NumCPU())
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+75
View File
@@ -0,0 +1,75 @@
"""Python worker(Locust 原生 HttpUser):4 类交易请求建模。
与 go/ 下的 boomer worker 跑**完全相同**的场景、请求体与用户池,
唯一差异是执行引擎(Python/GIL vs Go/goroutine),保证对比公平。
任务注册由 TASK_WEIGHTS 配置驱动(避免把任务硬写死在入口导致漏注册)。
"""
import os
import random
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import stats_dump # noqa: F401,E402 (注册 quitting 落盘监听)
from locust import HttpUser, between, task # noqa: E402
USER_POOL_SIZE = 1000 # 真随机用户池:避免全员压同一用户导致分布失真
TASK_WEIGHTS = { # 配置驱动,改权重不用动代码
"limit_open": 4,
"market_quantity_open": 2,
"market_amount_open": 2,
"batch_cancel": 1,
}
class TraderUser(HttpUser):
wait_time = between(0.001, 0.005) # 尽量压满,把瓶颈暴露给 worker 侧
def on_start(self):
self.user_id = random.randint(1, USER_POOL_SIZE)
self.open_orders = []
def _payload(self, with_price=True):
p = {
"user_id": self.user_id,
"contract_id": random.choice([1, 2, 3]),
"side": random.choice(["ask", "bid"]),
"margin_type": random.choice([1, 2]),
"quantity": str(random.randint(1, 50)),
}
if with_price:
p["price"] = str(round(random.uniform(28000, 32000), 2))
return p
@task(TASK_WEIGHTS["limit_open"])
def limit_open(self):
with self.client.post("/api/v1/order/limit/open",
json=self._payload(),
catch_response=True,
name="/api/v1/order/limit/open") as r:
if r.status_code == 200 and r.json().get("code") == 0:
self.open_orders.append(r.json()["data"]["order_id"])
else:
r.failure(f"biz error: {r.text[:100]}")
@task(TASK_WEIGHTS["market_quantity_open"])
def market_quantity_open(self):
self.client.post("/api/v1/order/market/quantity/open",
json=self._payload(with_price=False),
name="/api/v1/order/market/quantity/open")
@task(TASK_WEIGHTS["market_amount_open"])
def market_amount_open(self):
self.client.post("/api/v1/order/market/amount/open",
json=self._payload(with_price=False),
name="/api/v1/order/market/amount/open")
@task(TASK_WEIGHTS["batch_cancel"])
def batch_cancel(self):
ids, self.open_orders = self.open_orders[:10], self.open_orders[10:]
self.client.request("DELETE", "/api/v1/order/batch/cancel",
json={"user_id": self.user_id,
"order_ids": ids or [0]},
name="/api/v1/order/batch/cancel")
+21
View File
@@ -0,0 +1,21 @@
"""Go worker 压测时的 Locust master 入口。
master 本身不执行请求(负载由 boomer worker 产生),只需一个 User 类占位,
并复用 stats_dump 在 quitting 时落 JSON 结果。
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import stats_dump # noqa: F401,E402
from locust import HttpUser, task # noqa: E402
class PlaceholderUser(HttpUser):
"""占位 User:master 不跑任务,真实 task 在 boomer worker 侧注册。"""
@task
def noop(self):
pass
+70
View File
@@ -0,0 +1,70 @@
"""Locust 统计落盘插件:run 结束时把 stats 序列化为 JSON 到 results/。
供 python worker 与 go worker(master 侧)共用 —— go 压测时统计也在 master 汇总,
所以两份 locustfile 都 import 本模块。文件名前缀由环境变量 PERF_WORKER 决定。
"""
import json
import os
import time
from locust import events
RESULTS_DIR = os.path.join(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))), "results")
def _serialize(environment):
stats = environment.stats
entries = []
for e in stats.entries.values():
entries.append({
"name": e.name,
"method": e.method,
"num_requests": e.num_requests,
"num_failures": e.num_failures,
"avg_response_time": round(e.avg_response_time, 3),
"min_response_time": e.min_response_time,
"max_response_time": e.max_response_time,
"p50": round(e.get_response_time_percentile(0.50), 3),
"p95": round(e.get_response_time_percentile(0.95), 3),
"p99": round(e.get_response_time_percentile(0.99), 3),
"rps": round(e.total_rps, 3),
})
total = stats.total
doc = {
"worker": os.environ.get("PERF_WORKER", "unknown"),
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
"load": {
"users": getattr(environment.parsed_options, "num_users", None),
"run_time": getattr(environment.parsed_options, "run_time", None),
"host": getattr(environment.parsed_options, "host", None),
},
"total": {
"num_requests": total.num_requests,
"num_failures": total.num_failures,
"avg_response_time": round(total.avg_response_time, 3),
"p50": round(total.get_response_time_percentile(0.50), 3),
"p95": round(total.get_response_time_percentile(0.95), 3),
"p99": round(total.get_response_time_percentile(0.99), 3),
"rps": round(total.total_rps, 3),
},
"entries": entries,
}
label = os.environ.get("PERF_LABEL")
if label:
# 实验参数透传(如 scale 实验的 instances/max_qps),写进结果便于报告核对
doc["label"] = label
return doc
@events.quitting.add_listener
def _dump(environment, **kwargs):
if environment.parsed_options and environment.parsed_options.worker:
return # worker 进程不落盘
os.makedirs(RESULTS_DIR, exist_ok=True)
worker = os.environ.get("PERF_WORKER", "unknown")
path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(_serialize(environment), f, ensure_ascii=False, indent=2)
print(f"\n[stats] written to {path}")
+94
View File
@@ -0,0 +1,94 @@
# perf-harness-demo 对比报告
> 生成自 24 份真实压测结果:`results/go-1789962012.json`, `results/go-1790009273.json`, `results/go-1790010541.json`, `results/go-1790054848.json`, `results/go-1790055182.json`, `results/live_trigger-1790009033.json`, `results/live_trigger-1790010331.json`, `results/live_trigger-1790054558.json`, `results/python-1789961949.json`, `results/python-1790009211.json`, `results/python-1790010434.json`, `results/python-1790054714.json`, `results/python-1790055119.json`, `results/scale-1-1790009085.json`, `results/scale-1-1790010617.json`, `results/scale-1-1790054950.json`, `results/scale-1-1790055215.json`, `results/scale-4-1790009118.json`, `results/scale-4-1790010691.json`, `results/scale-4-1790055053.json`, `results/scale-4-1790055249.json`, `results/stale_trigger-1790009032.json`, `results/stale_trigger-1790010330.json`, `results/stale_trigger-1790054558.json`
## 0. 数字口径(先读这一节)
| 口径 | 环境 | 数字 |
|---|---|---|
| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** | 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS |
| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 |
> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台,单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。
## 1. 负载参数(公平性核对)
| worker | users | run_time | host |
|---|---|---|---|
| go | 50 | 60 | http://127.0.0.1:18099 |
| go | 50 | 60 | http://127.0.0.1:18099 |
| go | 50 | 60 | http://127.0.0.1:18099 |
| go | 50 | 60 | http://127.0.0.1:18099 |
| go | 50 | 60 | http://127.0.0.1:18099 |
| python | 50 | 60 | http://127.0.0.1:18099 |
| python | 50 | 60 | http://127.0.0.1:18099 |
| python | 50 | 60 | http://127.0.0.1:18099 |
| python | 50 | 60 | http://127.0.0.1:18099 |
| python | 50 | 60 | http://127.0.0.1:18099 |
两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求,权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。
## 2. 指标对比(每 worker 取最近一轮)
| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) |
|---|---|---|---|---|---|---|
| go | 1181444 | 0.00% | 20024.5 | 2 | 5 | 8 |
| python | 298351 | 0.00% | 4980.2 | 5 | 7 | 9 |
**Go worker TPS 是 Python worker 的 4.02 倍**(20024 vs 4980,同并发同场景)。
## 3. 分 endpoint 明细
### go
| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) |
|---|---|---|---|---|---|
| DELETE /api/v1/order/batch/cancel | 131815 | 0 | 2234.2 | 5 | 8 |
| POST /api/v1/order/limit/open | 523948 | 0 | 8880.5 | 5 | 8 |
| POST /api/v1/order/market/amount/open | 262600 | 0 | 4450.8 | 5 | 8 |
| POST /api/v1/order/market/quantity/open | 263081 | 0 | 4459.0 | 5 | 8 |
### python
| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) |
|---|---|---|---|---|---|
| DELETE /api/v1/order/batch/cancel | 33109 | 0 | 552.7 | 7 | 9 |
| POST /api/v1/order/limit/open | 132585 | 0 | 2213.2 | 7 | 9 |
| POST /api/v1/order/market/amount/open | 66841 | 0 | 1115.7 | 7 | 9 |
| POST /api/v1/order/market/quantity/open | 65816 | 0 | 1098.6 | 7 | 9 |
## 4. 归因分析
- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL,requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。
- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数),网络 I/O 走 netpoller,无全局锁;连接池调优后(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效),单机轻松压出数倍 TPS。
- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。本报告数字即按此判读。
- **本轮判读**:TPS 比 4.02 → 瓶颈在 **Python worker 侧(GIL)**。
## 5. 失真对比实验(条件单触发率)
两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`),负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动(contract 1 ≈ 31000 ± 1%)。
| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 |
|---|---|---|---|---|---|---|
| stale_trigger | hardcoded_low | 触发价写死 30500(低于行情区间) | 300 | 0 | 300 | 100.00% |
| stale_trigger | hardcoded_high | 触发价写死 31500(高于行情区间) | 300 | 0 | 0 | 0.00% |
| live_trigger | cache_driven | 触发价=实时标记价±20(缓存服务驱动) | 300 | 0 | 166 | 55.33% |
**判读**:
- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟),**每一轮都「一切正常」**。
- 但写死触发价的相位触发率塌缩到 **100% 与 0%**:市场状态稍偏离写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义,而报表上看不出任何问题(「数据是错的,但看起来是对的」)。
- 缓存服务实时驱动的触发率为 **55.33%**,落在由行情波动决定的中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。
- 缓存服务的滑动窗口去重 / 断流回退语义由 `tests/test_mark_price_service.py` 钉死;触发判定方向由 `tests/test_condition_trigger.py` 钉死。
## 6. 横向扩展实验(单实例上限 → 多实例)
被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**(worker / 并发 / 时长 / 单实例上限,见「参数」列)。
| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 |
|---|---|---|---|---|---|---|---|
| 1 | 14696 | 0.00% | 506.8 | 200 | 200 | 200 | instances=1 max_qps=500/instance extra_latency=2ms users=100 |
| 4 | 58752 | 0.00% | 2025.9 | 49 | 52 | 53 | instances=4 max_qps=500/instance extra_latency=2ms users=100 |
**4 实例 TPS / 1 实例 TPS = 4.00**(2026 vs 507;不要求线性 —— 分流器与 loopback 也会吃一份,TPS 随实例数上升即说明扩展是有效的)。
- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**,不是一句「慢」;扩展实例数的决策依据正是这个数字。
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+72
View File
@@ -0,0 +1,72 @@
{
"worker": "go",
"timestamp": "2026-09-21T11:40:12",
"load": {
"users": 50,
"run_time": 60,
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 1204302,
"num_failures": 0,
"avg_response_time": 1.899,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 20411.898
},
"entries": [
{
"name": "/api/v1/order/market/quantity/open",
"method": "POST",
"num_requests": 267432,
"num_failures": 0,
"avg_response_time": 1.898,
"min_response_time": 0,
"max_response_time": 41,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4532.746
},
{
"name": "/api/v1/order/limit/open",
"method": "POST",
"num_requests": 536115,
"num_failures": 0,
"avg_response_time": 1.9,
"min_response_time": 0,
"max_response_time": 44,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 9086.695
},
{
"name": "/api/v1/order/market/amount/open",
"method": "POST",
"num_requests": 267098,
"num_failures": 0,
"avg_response_time": 1.896,
"min_response_time": 0,
"max_response_time": 44,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4527.085
},
{
"name": "/api/v1/order/batch/cancel",
"method": "DELETE",
"num_requests": 133657,
"num_failures": 0,
"avg_response_time": 1.905,
"min_response_time": 0,
"max_response_time": 45,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 2265.373
}
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"worker": "go",
"timestamp": "2026-09-22T00:47:53",
"load": {
"users": 50,
"run_time": 60,
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 1178990,
"num_failures": 0,
"avg_response_time": 1.952,
"p50": 1,
"p95": 6,
"p99": 8,
"rps": 19649.833
},
"entries": [
{
"name": "/api/v1/order/market/amount/open",
"method": "POST",
"num_requests": 261974,
"num_failures": 0,
"avg_response_time": 1.952,
"min_response_time": 0,
"max_response_time": 44,
"p50": 1,
"p95": 6,
"p99": 8,
"rps": 4366.233
},
{
"name": "/api/v1/order/market/quantity/open",
"method": "POST",
"num_requests": 261443,
"num_failures": 0,
"avg_response_time": 1.96,
"min_response_time": 0,
"max_response_time": 45,
"p50": 2,
"p95": 6,
"p99": 8,
"rps": 4357.383
},
{
"name": "/api/v1/order/batch/cancel",
"method": "DELETE",
"num_requests": 130859,
"num_failures": 0,
"avg_response_time": 1.95,
"min_response_time": 0,
"max_response_time": 33,
"p50": 1,
"p95": 6,
"p99": 8,
"rps": 2180.983
},
{
"name": "/api/v1/order/limit/open",
"method": "POST",
"num_requests": 524714,
"num_failures": 0,
"avg_response_time": 1.949,
"min_response_time": 0,
"max_response_time": 36,
"p50": 1,
"p95": 6,
"p99": 8,
"rps": 8745.233
}
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"worker": "go",
"timestamp": "2026-09-22T01:09:01",
"load": {
"users": 50,
"run_time": 60,
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 1207984,
"num_failures": 0,
"avg_response_time": 1.882,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 20474.305
},
"entries": [
{
"name": "/api/v1/order/limit/open",
"method": "POST",
"num_requests": 536645,
"num_failures": 0,
"avg_response_time": 1.881,
"min_response_time": 0,
"max_response_time": 39,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 9095.678
},
{
"name": "/api/v1/order/market/amount/open",
"method": "POST",
"num_requests": 268468,
"num_failures": 0,
"avg_response_time": 1.882,
"min_response_time": 0,
"max_response_time": 35,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4550.305
},
{
"name": "/api/v1/order/market/quantity/open",
"method": "POST",
"num_requests": 268488,
"num_failures": 0,
"avg_response_time": 1.881,
"min_response_time": 0,
"max_response_time": 36,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4550.644
},
{
"name": "/api/v1/order/batch/cancel",
"method": "DELETE",
"num_requests": 134383,
"num_failures": 0,
"avg_response_time": 1.889,
"min_response_time": 0,
"max_response_time": 36,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 2277.678
}
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"worker": "go",
"timestamp": "2026-09-22T13:27:28",
"load": {
"users": 50,
"run_time": 60,
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 1224254,
"num_failures": 0,
"avg_response_time": 1.845,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 20750.068
},
"entries": [
{
"name": "/api/v1/order/limit/open",
"method": "POST",
"num_requests": 543420,
"num_failures": 0,
"avg_response_time": 1.847,
"min_response_time": 0,
"max_response_time": 38,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 9210.508
},
{
"name": "/api/v1/order/batch/cancel",
"method": "DELETE",
"num_requests": 136373,
"num_failures": 0,
"avg_response_time": 1.848,
"min_response_time": 0,
"max_response_time": 44,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 2311.407
},
{
"name": "/api/v1/order/market/quantity/open",
"method": "POST",
"num_requests": 272441,
"num_failures": 0,
"avg_response_time": 1.843,
"min_response_time": 0,
"max_response_time": 34,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4617.644
},
{
"name": "/api/v1/order/market/amount/open",
"method": "POST",
"num_requests": 272020,
"num_failures": 0,
"avg_response_time": 1.843,
"min_response_time": 0,
"max_response_time": 35,
"p50": 1,
"p95": 5,
"p99": 8,
"rps": 4610.508
}
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"worker": "go",
"timestamp": "2026-09-22T13:33:02",
"load": {
"users": 50,
"run_time": 60,
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 1181444,
"num_failures": 0,
"avg_response_time": 1.939,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 20024.475
},
"entries": [
{
"name": "/api/v1/order/market/quantity/open",
"method": "POST",
"num_requests": 263081,
"num_failures": 0,
"avg_response_time": 1.935,
"min_response_time": 0,
"max_response_time": 52,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 4459.0
},
{
"name": "/api/v1/order/batch/cancel",
"method": "DELETE",
"num_requests": 131815,
"num_failures": 0,
"avg_response_time": 1.941,
"min_response_time": 0,
"max_response_time": 37,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 2234.153
},
{
"name": "/api/v1/order/limit/open",
"method": "POST",
"num_requests": 523948,
"num_failures": 0,
"avg_response_time": 1.94,
"min_response_time": 0,
"max_response_time": 56,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 8880.475
},
{
"name": "/api/v1/order/market/amount/open",
"method": "POST",
"num_requests": 262600,
"num_failures": 0,
"avg_response_time": 1.94,
"min_response_time": 0,
"max_response_time": 53,
"p50": 2,
"p95": 5,
"p99": 8,
"rps": 4450.847
}
]
}
+47
View File
@@ -0,0 +1,47 @@
{
"worker": "live_trigger",
"timestamp": "2026-09-22T00:43:53",
"load": {
"users": 10,
"run_time": "300 req",
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.81,
"p50": 1.489,
"p95": 3.806,
"p99": 8.439,
"rps": 2845.399
},
"entries": [
{
"name": "/api/v1/order/condition/open",
"method": "POST",
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.81,
"p50": 1.489,
"p95": 3.806,
"p99": 8.439,
"rps": 2845.399
}
],
"trigger": {
"mode": "live",
"phases": [
{
"name": "cache_driven",
"detail": "触发价=实时标记价±20(缓存服务驱动)",
"requests": 300,
"failures": 0,
"triggered": 153,
"trigger_rate": 0.51,
"p50": 1.489,
"p95": 3.806,
"p99": 8.439
}
]
}
}
+47
View File
@@ -0,0 +1,47 @@
{
"worker": "live_trigger",
"timestamp": "2026-09-22T01:05:31",
"load": {
"users": 10,
"run_time": "300 req",
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.694,
"p50": 1.49,
"p95": 3.175,
"p99": 5.049,
"rps": 2941.507
},
"entries": [
{
"name": "/api/v1/order/condition/open",
"method": "POST",
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.694,
"p50": 1.49,
"p95": 3.175,
"p99": 5.049,
"rps": 2941.507
}
],
"trigger": {
"mode": "live",
"phases": [
{
"name": "cache_driven",
"detail": "触发价=实时标记价±20(缓存服务驱动)",
"requests": 300,
"failures": 0,
"triggered": 145,
"trigger_rate": 0.4833,
"p50": 1.49,
"p95": 3.175,
"p99": 5.049
}
]
}
}
+47
View File
@@ -0,0 +1,47 @@
{
"worker": "live_trigger",
"timestamp": "2026-09-22T13:22:38",
"load": {
"users": 10,
"run_time": "300 req",
"host": "http://127.0.0.1:18099"
},
"total": {
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.804,
"p50": 1.696,
"p95": 3.125,
"p99": 3.866,
"rps": 2940.055
},
"entries": [
{
"name": "/api/v1/order/condition/open",
"method": "POST",
"num_requests": 300,
"num_failures": 0,
"avg_response_time": 1.804,
"p50": 1.696,
"p95": 3.125,
"p99": 3.866,
"rps": 2940.055
}
],
"trigger": {
"mode": "live",
"phases": [
{
"name": "cache_driven",
"detail": "触发价=实时标记价±20(缓存服务驱动)",
"requests": 300,
"failures": 0,
"triggered": 166,
"trigger_rate": 0.5533,
"p50": 1.696,
"p95": 3.125,
"p99": 3.866
}
]
}
}

Some files were not shown because too many files have changed in this diff Show More